Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript setTimeout() not working [closed]

Tags:

javascript

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> 
like image 715
James Dorfman Avatar asked Jan 02 '14 20:01

James Dorfman


People also ask

Why is setTimeout not working?

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.

Is JavaScript setTimeout blocking?

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.

How do I close setTimeout?

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.

What is the alternative for setTimeout in JavaScript?

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.


2 Answers

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); 
like image 135
linstantnoodles Avatar answered Oct 13 '22 23:10

linstantnoodles


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); 
like image 39
Matt Catellier Avatar answered Oct 13 '22 22:10

Matt Catellier