Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

113
Vistas
How to create a function with a parameter to be passed

I’m just trying to create a function with a parameter, but it says that the parameter is undefined.

It’ll be clearer with the example:

const txt = ["Some text here"];
let textPosition = 0;
const speed = 25;

function typeWriter(element) {
  document.getElementById("paragraph1").innerHTML = element[0].substring(0, textPosition);
  if(textPosition++ != element[0].length) {
    setTimeout(typeWriter, speed);
  } else {
    CallButton.classList.toggle("hidden");
  }
};

typeWriter(txt);
<span id="paragraph1"></span>

So I’m clearly doing something wrong here, but I do not know what and why.

The code should simply insert in paragraph1 the string in the txt array in a typewriter style. It is working when I replace element with txt.

But since I need to call the same function multiple times for different text, so different arrays with different text in each, I need to pass a parameter, so that I can reuse the function.

const txt = ["Some text here"];
let textPosition = 0;
const speed = 25;

function typeWriter() {
  document.getElementById("paragraph1").innerHTML = txt[0].substring(0, textPosition);
  if(textPosition++ != txt[0].length) {
    setTimeout(typeWriter, speed);
  } 
};

typeWriter();
<span id="paragraph1"></span>

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

Replace setTimeout callback with arrow function passing element

const txt = ["Some text here"];
let textPosition = 0;
const speed = 25;

function typeWriter(element) {
  document.getElementById("paragraph1").innerHTML = element[0].substring(0, textPosition);
  if(textPosition++ != element[0].length) {
    setTimeout(() => typeWriter(element), speed);
  } else {
    CallButton.classList.toggle("hidden");
  }
};

typeWriter(txt);
<span id="paragraph1"></span>

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda