0

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>

4
  • 3
    setTimeout(typeWriter, speed); there won't be any arguments passed, when called here. Commented Apr 10, 2022 at 14:43
  • Why? You mean that the function is actually called with setTimeout? Commented Apr 10, 2022 at 14:51
  • It's a recursion, basically it keeps calling itself with a small delay (speed) until the base case is reached textPosition++ === txt[0].length . Commented Apr 10, 2022 at 14:57
  • Ok but why can’t I pass arguments? What would be a solution to achieve the goal? Commented Apr 10, 2022 at 16:25

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

It’s just another element of the code that shouldn’t impact anything, but I put it there in case someone would spot a typo/mistake/etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.