Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout appears to execute too fast

I've been fiddling around with setTimeout and setInterval, and I cannot get the code to execute the way I would like it to. My goal is to create a setInterval, which calls once every three seconds, and have it clear after ten seconds. However, when I run the code in firebug, the only thing I get is a number, which I assume is the id of setInterval because every time I execute the code, the number increases.

var intID = setInterval(function() {
    console.log("I've been called");},3000);


setTimeout(clearInterval(intID), 10000);
like image 904
Nick Litwin Avatar asked Jun 20 '14 23:06

Nick Litwin


People also ask

Why does setTimeout run immediately?

This is because if you pass the parameters directly like this: setTimeout(greeting("Nathan", "Software developer"), 3000); Then JavaScript will immediately execute the function without waiting, because you're passing a function call and not a function reference as the first parameter.

Is there a limit for setTimeout?

Maximum delay value Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed integer internally. This causes an integer overflow when using delays larger than 2,147,483,647 ms (about 24.8 days), resulting in the timeout being executed immediately.

What can I use instead of setTimeout?

The setTimeout() is executed only once. If you need repeated executions, use setInterval() instead. Use the clearTimeout() method to prevent the function from starting.

Does setTimeout cause memory leak?

setTimeout and setInterval are the two timing events available in JavaScript. The setTimeout function executes when the given time is elapsed, whereas setInterval executes repeatedly for the given time interval. These timers are the most common cause of memory leaks.


1 Answers

This statement:

setTimeout(clearInterval(intID), 10000);

means, "call the function 'clearInterval' passing the value of variable 'intID', and then pass the return value of that and the number 10000 to the function 'setTimeout'."

In other words, you're calling the function "clearInterval" and then passing the returned value to setTimeout().

Instead, pass setTimeout() a function:

setTimeout(function() { clearInterval(intID); }, 10000);
like image 188
Pointy Avatar answered Sep 22 '22 17:09

Pointy