Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

112
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda