Open In App

JavaScript setTimeout() & setInterval() Method

Last Updated : 13 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

JavaScript SetTimeout and SetInterval are the only native function in JavaScript that is used to run code asynchronously, it means allowing the function to be executed immediately, there is no need to wait for the current execution completion, it will be for further execution.

setTimeout(gfg1, 2000);
function gfg1() {
    console.log("gfg1");
}
function gfg() {
    console.log("gfg");
}
setInterval(gfg, 1000);

Output:

gfg
gfg1
gfg
......

Key points:

  • gfg1 will be called once as setTimeout is set for 2 seconds
  • gfg function will called each second as it passed through the setInterval.

JavaScript setTimeout() Method

The setTimeout() Method executes a function, after waiting a specified number of milliseconds. 

setTimeout(gfg1, 2000);
function gfg1() {
    console.log("gfg1");
}

Output:

gfg1

JavaScript setInterval() Method

The setInterval() method repeats a given function at every given time interval. 

function gfg() {
    console.log("gfg");
}
setInterval(gfg, 1000);

Output: After every second a new “gfg” message will be displayed.

Interesting Facts

  • Asynchronous Execution: Both methods are asynchronous, meaning the browser doesn’t block other code execution while waiting for the timer.
  • Return Value: Both methods return a unique identifier (ID), which can be used with clearTimeout() or clearInterval() to stop the scheduled task.
  • Timer Accuracy: Timers are not perfectly precise; delays can vary due to browser limitations and other queued tasks.
  • Infinite Intervals: Using setInterval() without a clearInterval() call can lead to infinite loops, potentially causing performance issues.
  • Nested Timers: A setTimeout() can mimic a setInterval() by recursively calling itself after each execution.
  • Minimum Delay: The minimum delay for setTimeout() or setInterval() is 4 milliseconds, though it may increase in inactive browser tabs for performance reasons.
  • Timer in Node.js: Both methods are also available in Node.js with similar behavior but are part of the global object.

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.



Next Article

Similar Reads

three90RightbarBannerImg