Explain Codes LogoExplain Codes Logo

How to set time delay in javascript

javascript
async-await
setTimeout
event-loop
Nikita BarsukovbyNikita Barsukov·Feb 21, 2025
TLDR

Use setTimeout() in JavaScript to delay the execution of function:

setTimeout(() => console.log("Waited, but still arrived."), 2000);

The setTimeout() function accepts a callback function and a delay in milliseconds (2000 for 2 seconds). It's like telling JavaScript: "Hey, could you please do this, but with a bit of a delay?".

As easy as riding a bike...with a delay

Imagine you've just bought a new bike. It's shiny, it's fast, but there's a catch: it only starts moving 3 seconds after you start pedalling.

The Bike = Your Function The Delay = `setTimeout()`

Your bike in action:

setTimeout(() => { 🚲.move(); }, 3000); // The bike starts moving after 3 seconds!

Visualized ride:

Now: [🅿️🚲]------ wait for 3s (⏲) ------> Future: [🚴‍♀️] # The bike waits patiently while you pedal in vain for 3 seconds, then suddenly rockets forward!

Implementing a function delay

Creating a 1000ms delay before some action, like a sound effect on a button, can make your interface feel a bit more lively:

let isBtnClicked = false; button.addEventListener('click', () => { if(isBtnClicked){ setTimeout(() => { // play sound effect isBtnClicked = false; //Ready for the next click }, 1000); //Delay: 1 second } });

Clean delays with async/await

The async/await syntax allows for a more seamless code layout to control the sequence of asynchronous operations:

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); async function delayedAction(){ await sleep(3000); //Wait for 3 seconds console.log("You've been waiting for this log!"); //System: console.log('Done!') would've been too mainstream } delayedAction();

Timeout management with clearTimeout

Being able to cancel an ongoing timeout can be really handy:

const delayId = setTimeout(() => { /* some delayed reaction */ }, 3000); // Next scene: Regret clearTimeout(delayId); // Delay? What delay?

Recursive setTimeout for repeated delays

A recursive function combined with setTimeout can be used to set up repeated delays with style:

function delayedTask() { // What tasks? Tasks appear after delay setTimeout(delayedTask, 3000); } delayedTask(); // Start of an epic cycle of delays

Synchronous delays: The not-so-good practice

Simulating a synchronous delay or "sleep" function in JavaScript is like trying to pause a movie by yelling at the screen. We can definitely try, but it's not recommended:

function sleep(ms) { const date = Date.now(); let currentDate = null; do { currentDate = Date.now(); } while (currentDate - date < ms); } sleep(2000); // The code froze for 2 seconds because it was 'asleep'. Get it?

JavaScript's event loop, setTimeout, and async behavior are all interconnected. When a delay is defined, execution of following code isn't stopped. Rather, the function inside setTimeout waits for its turn to execute after the specified delay.