MOCKSTACKS
EN
Questions And Answers

More Tutorials









Javascript Intervals and Timeouts

To repeat a function indefinitely, setTimeout can be called recursively:


function repeatingFunc() {
 console.log("It's been 5 seconds. Execute the function again.");
 setTimeout(repeatingFunc, 5000);
}
setTimeout(repeatingFunc, 5000);

Unlike setInterval, this ensures that the function will execute even if the function's running time is longer than the specified delay. However, it does not guarantee a regular interval between function executions. This behaviour also varies because an exception before the recursive call to setTimeout will prevent it from repeating again, while setInterval would repeat indefinitely regardless of exceptions.


Intervals


function waitFunc(){
 console.log("This will be logged every 5 seconds");
}
window.setInterval(waitFunc,5000);

Standard


You don't need to create the variable, but it's a good practice as you can use that variable with clearInterval to stop the currently running interval


var int = setInterval("doSomething()", 5000 ); /* 5 seconds */
var int = setInterval(doSomething, 5000 ); /* same thing, no quotes, no parens */

If you need to pass parameters to the doSomething function, you can pass them as additional parameters beyond
the first two to setInterval.


Without overlapping

setInterval, as above, will run every 5 seconds (or whatever you set it to) no matter what. Even if the function doSomething takes long than 5 seconds to run. That can create issues. If you just want to make sure there is that pause in between runnings of doSomething, you can do this:


(function(){
 doSomething();
 setTimeout(arguments.callee, 5000);
})()

Removing intervals

window.setInterval() returns an IntervalID, which can be used to stop that interval from continuing to run. To do this, store the return value of window.setInterval() in a variable and call clearInterval() with that variable as the only argument:


function waitFunc(){
 console.log("This will be logged every 5 seconds");
}
var interval = window.setInterval(waitFunc,5000);
window.setTimeout(function(){
 clearInterval(interval);
},32000);

This will log This will be logged every 5 seconds every 5 seconds, but will stop it after 32 seconds. So it will log the message 6 times.


Removing timeouts

window.setTimout() returns a TimeoutID, which can be used to stop that timeout from running. To do this, store the return value of window.setTimeout() in a variable and call clearTimeout() with that variable as the only argument:


function waitFunc(){
 console.log("This will not be logged after 5 seconds");
}
function stopFunc(){
 clearTimeout(timeout);
}
var timeout = window.setTimeout(waitFunc,5000);
window.setTimeout(stopFunc,3000);

This will not log the message because the timer is stopped after 3 seconds.


setTimeout, order of operations, clearTimeout

setTimeout

  • Executes a function, after waiting a specified number of milliseconds.
  • used to delay the execution of a function.

  • Syntax : setTimeout(function, milliseconds) or window.setTimeout(function, milliseconds)

    This example outputs "hello" to the console after 1 second. The second parameter is in milliseconds, so
    1000 = 1 sec, 250 = 0.25 sec, etc

    setTimeout(function() {
     console.log('hello');
    }, 1000);

    Order of operations

    Additionally though, due to the fact that JavaScript is single threaded and uses a global event loop, setTimeout can be used to add an item to the end of the execution queue by calling setTimeout with zero delay. For example:


    setTimeout(function() {
     console.log('world');
    }, 0);
    console.log('hello');

    Output

    hello
    world

    Also, zero milliseconds here does not mean the function inside the setTimeout will execute immediately. It will take slightly more than that depending upon the items to be executed remaining in the execution queue. This one is just pushed to the end of the queue.


    Cancelling a timeout

    clearTimeout() : stops the execution of the function specified in setTimeout()
    Syntax : clearTimeout(timeoutVariable) or window.clearTimeout(timeoutVariable)


    Example

    var timeout = setTimeout(function() {
     console.log('hello');
    }, 1000);
    clearTimeout(timeout);

    Output

    The timeout will no longer be executed


    Conclusion

    In this page (written and validated by ) you learned about Javascript Intervals and Timeouts . What's Next? If you are interested in completing Javascript tutorial, your next topic will be learning about: Javascript Cookies.



    Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


    Share On:


    Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.