How to set time delay in JavaScript

JavaScript's nature as a scripting language and the concept of synchronous, single-threaded execution. While it's generally discouraged to introduce blocking delays in the execution flow, there are legitimate scenarios where controlled time delays are needed to achieve specific behaviors. In such cases, JavaScript provides various functions and methods to facilitate these timed actions.

These functions allow developers to perform actions, introduce pauses, and subsequently carry out further actions, enhancing the interactive behavior of JavaScript applications. It's important to use these mechanisms thoughtfully and avoid introducing unnecessary blocking delays in the execution flow.


How to Sleep/Wait/Delay in Code Execution | JavaScript

Setting a time delay in JavaScript can be achieved using the setTimeout() and setInterval() functions. These functions allow you to schedule the execution of code after a certain amount of time. Here's a detailed explanation along with examples for both methods:

Javascript setTimeout()

The first and the most common method in implementing a delay in the execution of a JavaScript code is to use the setTimeOut() method.

setTimeout( function , delay in ms)
  1. functionname - The function name for the function to be executed.
  2. milliseconds - The number of milliseconds.
run this source code Browser View

Full Source | JavaScript
var delayInMilliseconds = 5000; //4 second console.log('Waiting for 5 sec...') setTimeout(function() { console.log('code to be executed after 5 second...') }, delayInMilliseconds);

Javascript setInterval()

JavaScript's setTimeout() executes only once after the specified delay, whereas setInterval() repeatedly calls the callback function at regular intervals. Both of these methods return an integer identifier that can be used to clear the scheduled execution before the timer expires. The setInterval() method continues calling the function until clearInterval() is invoked or the window is closed."

setInterval(function, milliseconds);
  1. functionname - The function name for the function to be executed.
  2. milliseconds - The number of milliseconds.
run this source code Browser View

Full Source | JavaScript
var intervalID = setInterval(function(){ //called 5 times each time after one second //before getting cleared by below timeout. console.log("Calling after every 1 second"); },1000); //delay is in milliseconds
setTimeout(function(){ clearInterval(intervalID); //clear above interval after 5 seconds console.log('This code to be executed after 5 second...') },5000);
Output:
Program start here.... Calling after every 1 second Calling after every 1 second Calling after every 1 second Calling after every 1 second Calling after every 1 second This code to be executed after 5 second...

Javascript sleep()

JavaScript has undergone substantial evolution, enabling the simulation of the sleep() function through various approaches. The introduction of features like promises and async/await functions in JavaScript has greatly facilitated the utilization of the sleep() function, streamlining its implementation. These advancements offer more convenient ways to introduce delays and manage asynchronous behavior in JavaScript code.

sleep(Time in ms).then(() => { //// code })

Or as a one-liner:

await new Promise(r => setTimeout(r, 2000));

Or

const sleep = ms => new Promise(r => setTimeout(r, ms));

The sleep() function can be used along with the async/await to get the pause between the execution.

example
function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function demo() { for (let i = 0; i < 5; i++) { console.log("Waiting ${i} seconds..."); await sleep(i * 1000); } console.log('Done'); } demo();
Output:
Waiting 1 seconds... Waiting 2 seconds... Waiting 3 seconds... Waiting 4 seconds... Done

Clearing Timeout or Interval

To clear a timeout or interval, you can use the clearTimeout() and clearInterval() functions, respectively. These functions require the identifier returned by the original setTimeout() or setInterval() call.

const timeoutId = setTimeout(() => { console.log("This will never be executed."); }, 5000); clearTimeout(timeoutId); // Cancels the timeout before it fires

Conclusion

To introduce time delays in JavaScript, you can use the setTimeout() function for a one-time delay or the setInterval() function for repeated delays. These functions enable you to execute code after a specified time interval, enhancing the interactivity and behavior of your web applications. Remember to clear timeouts or intervals when necessary using clearTimeout() and clearInterval() to prevent unwanted execution.