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

Oldest comments (0)