Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

111
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!