Hi I'm trying to use the function setTimeout() in javascript except it's not working. Thanks in advance to anyone who can help.
<!DOCTPYE html> <html> <head> <script> var button = document.getElementById("reactionTester"); var start = document.getElementById("start"); function init() { var startInterval/*in milliseconds*/ = Math.floor(Math.random() * 30) * 1000; setTimeout(startTimer(), startInterval); } function startTimer() { document.write("hey"); } </script> </head> <body> <form id="form"> <input type="button id=" reactionTester" onclick="stopTimer()"> <input type="button" value="start" id="start" onclick="init()"> </form> </body> </html>
If you are requiring the setTimeout functions to execute on the dot, there can be some scenarios when this is not the case. Late timeouts or timeouts that execute inaccurately could be due the following issues: browser or OS is busy with other tasks.
Explanation: setTimeout() is non-blocking which means it will run when the statements outside of it have executed and then after one second it will execute. All other statements that are not part of setTimeout() are blocking which means no other statement will execute before the current statement finishes.
To cancel a setTimeout() method from running, you need to use the clearTimeout() method, passing the ID value returned when you call the setTimeout() method.
The setInterval method has the same syntax as setTimeout : let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...) All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time.
This line:
setTimeout(startTimer(), startInterval);
You're invoking startTimer()
. Instead, you need to pass it in as a function to be invoked, like so:
setTimeout(startTimer, startInterval);
If your in a situation where you need to pass parameters to the function you want to execute after timeout, you can wrap the "named" function in an anonymous function.
i.e. works
setTimeout(function(){ startTimer(p1, p2); }, 1000);
i.e. won't work because it will call the function right away
setTimeout( startTimer(p1, p2), 1000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With