Search code examples
javascriptecmascript-6settimeoutarrow-functions

How to set up timer in JavaScript by passing a parameter


I'm trying to set up the timeout using the HTML input box, and use this as a parameter to setTimeout.

It's a very simple task, but I'm not an JS developer, so I'm not sure on how to pass the parameter properly to the arrow function.

HTML code consists only of 2 elements.

<button id="myElementId">Click me</button>
<input id="milliseconds" type="number" placeholder="number of milliseconds"/>

And my JS code looks like:

const clickbutton = document.getElementById('myElementId');
const millis = parseInt(document.getElementById('milliseconds').value, 10);

clickbutton.addEventListener('click', (event) => {
    setTimeout(() => { alert("I work");
  }, millis); // <-- here I don't want to use a static value 
});

However it seems like I can't get the value of millis from outer scope inside the arrow function.

I also tried with passing the second argument:

const clickbutton = document.getElementById('myElementId');
const millis = parseInt(document.getElementById('milliseconds').value, 10);

clickbutton.addEventListener('click', (event, millis) => {
    setTimeout(() => { alert("I work");
  }, millis); 
});

with no luck there.

Any help is appreciated.

Thank you.


Solution

  • Get the value in the click event listener because otherwise it's not defined (it's only defined after you type something in the input and decide to click the button):

    const clickbutton = document.getElementById('myElementId');
    
    clickbutton.addEventListener('click', (event) => {
      const millis = parseInt(document.getElementById('milliseconds').value, 10);
      setTimeout(() => {
        alert("I work");
      }, millis);
    });
    <button id="myElementId">Click me</button>
    <input id="milliseconds" type="number" placeholder="number of milliseconds" />