How to set time delay in javascript
Use setTimeout()
in JavaScript to delay the execution of function:
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.
Your bike in action:
Visualized ride:
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:
Clean delays with async/await
The async/await
syntax allows for a more seamless code layout to control the sequence of asynchronous operations:
Timeout management with clearTimeout
Being able to cancel an ongoing timeout can be really handy:
Recursive setTimeout for repeated delays
A recursive function combined with setTimeout
can be used to set up repeated delays with style:
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:
Navigating the event loop
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.
Was this article helpful?