Language: EN

javascript-setinterval-settimeout

Using setInterval and setTimeout in JavaScript

In JavaScript, setInterval and setTimeout are one of the simplest ways to manage timing of tasks.

These two commonly used methods are an easy way to approach asynchronous programming.

  • setTimeout is used to delay the execution of a function just once.
  • setInterval is used to repeatedly execute code at regular intervals.

They are also available in both web browsers and most runtimes like NodeJs.

Both are suitable for simple timing tasks, but if the tasks are more complex and require finer control, it’s better to opt for Promises and the async/await syntax.

Internal workings

Both setTimeout and setInterval depend on the event loop of JavaScript, a mechanism that allows handling asynchronous tasks. When you use one of these functions:

  1. The scheduled task is registered in the task queue.
  2. Once the specified time has elapsed, the event loop places the function on the execution stack.
  3. The function executes when the execution stack is empty.

Delayed execution setTimeout

setTimeout is a function that executes a function or a block of code after a specified time. The basic syntax of setTimeout is:

let timeoutId = setTimeout(function, time, [arguments...]);
  • function: The function that will be executed after the time elapses.
  • time: The time in milliseconds before executing the function.
  • [arguments…]: Optionally, arguments that will be passed to the function.

Let’s see it with an example,

function greet() {
  console.log('Hello, world');
}

let timeoutId = setTimeout(greet, 2000); // Executes `greet` after 2 seconds

In this example, greet will execute after 2000 milliseconds (2 seconds).

Cancelling setTimeout

To cancel an action scheduled by setTimeout, use clearTimeout, passing the identifier returned by setTimeout.

function showNotification() {
  console.log('Important notification!');
}

let timeoutId = setTimeout(showNotification, 3000);

clearTimeout(timeoutId); // Cancels the notification before it shows

In this case, the call to clearTimeout prevents showNotification from executing after 3 seconds.

Periodic execution setInterval

setInterval is a function that allows executing a function or a block of code repeatedly at regular time intervals. The basic syntax of setInterval is:

let intervalId = setInterval(function, interval, [arguments...]);
  • function: The function that will be executed repeatedly.
  • interval: The time in milliseconds between each execution of the function.
  • [arguments…]: Optionally, arguments that will be passed to the function.

Let’s see it with an example,

function greet() {
  console.log('Hello, world');
}

let intervalId = setInterval(greet, 1000); // Executes `greet` every second

In this example, greet will execute every second due to the 1000-millisecond interval.

Cancelling setInterval

To stop the repetitive execution started by setInterval, use clearInterval, passing the identifier returned by setInterval.

function greet() {
  console.log('Hello, world');
}

let intervalId = setInterval(greet, 1000);

setTimeout(() => {
  clearInterval(intervalId); // Stops the execution of `greet` after 5 seconds
}, 5000);

In this example, greet executes every second, but clearInterval stops the repetition after 5 seconds.

Replacement with promises

When you need to synchronize multiple tasks that depend on time, consider using Promise along with async/await for more precise control and better error handling.

function wait(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function runTasks() {
  console.log('Start');
  await wait(2000); // Waits for 2 seconds
  console.log('After 2 seconds');
}

runTasks();

In this example,

  • wait creates a promise that resolves after a specified delay
  • await is used to pause the execution of runTasks.

Considerations and best practices

  • Timer accuracy: setInterval and setTimeout do not guarantee execution accuracy to the millisecond. The specified time is a minimum time, not an exact time.
    The function may not execute exactly at the end of the interval due to the nature of the event loop and system load.

  • Avoid nesting: Using setTimeout and setInterval can make your code hard to manage if you nest them too much.

  • Memory leaks: Remember to clear intervals and timeouts when they are no longer needed. If you leave active intervals without canceling them, you can create memory leaks.