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.
const millis = ...line inside the timout function, else it wont pick up the value, insteadmilliswill just be null on loadmilliswill not extend into the future. With your code,milliswill remain at whatever value it gets set to at the time the line of code runs, even if you hadn't mistakenly usedconstfor a value that's supposed to change. One way to fix this is to turn it into a function: jsfiddle.net/khrismuc/m1xqL8ys