DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for setTimeout() & setInterval() in javascript
Aishanii
Aishanii

Posted on

setTimeout() & setInterval() in javascript

As we discussed earlier setTimeout() starts it's timer and goes to task queue and waits until the call stack is empty. This is all a part of the event loop working.

setTimeout()

Example code:

function sayHi() {
  alert('Hello');
}

setTimeout(sayHi, 10000);
Enter fullscreen mode Exit fullscreen mode

Here sayHi function is executed after a delay of 10000 ms.

setTimeout() doesn't necessarily execute the callback function precisely after the time inserted.

As it waits for the call stack to be empty, it might be the case that the timer has already expired while waiting, which means it will execute after a while and not the time mentioned.

Hence,


function sayHi() {
  alert('Hello');
}

setTimeout(sayHi, 0);
.
.
.
Enter fullscreen mode Exit fullscreen mode

Even here, it will wait till the whole program is executed and call stack is empty.

By remaining in task queue, it makes sure to avoid thread blocking. So:

  • It waits atleast the time mentioned to execute the callback.
  • It does not block the main thread.

setInterval()

It keeps on executing the callback function after given interval until stopped.

let timerId = setInterval(() => console.log('attention'), 2000);

setTimeout(() => { clearInterval(timerId); console.log('stop'); }, 5000);
Enter fullscreen mode Exit fullscreen mode

Image description

Here, the 'attention' is printed after every 2 seconds and it's cleared using clearInterval() below after 5 seconds, that is when stop is printed.

Learn more about concurrency in javascript and how can setTimeout(0) is used.
🌟setTimeout() by Akshay Saini

Latest comments (0)

Timeless DEV post...

How to write a kickass README

Arguably the single most important piece of documentation for any open source project is the README. A good README not only informs people what the project does and who it is for but also how they use and contribute to it.

If you write a README without sufficient explanation of what your project does or how people can use it then it pretty much defeats the purpose of being open source as other developers are less likely to engage with or contribute towards it.