DEV Community

Arul .A
Arul .A

Posted on

Difference between setTimeout and setInterval?

setTimeout :

  • It runs a function once after a specified delay.

  • Doesn’t repeat automatically,must be called again manually.

  • Used for Delayed execution tasks.

  • Typically used for one-time events (API retry, alerts)

Example:

setTimeout(() => console.log("Runs once"), 2000);
Enter fullscreen mode Exit fullscreen mode

setInterval :

  • It runs a function repeatedly at a fixed time interval until stopped.

  • It Continues until clearInterval().

  • Used for recurrying tasks.

  • Typically used for polling, clocks, repeating checks.

Example:

setInterval(() => console.log("Runs repeatedly"), 2000);

Enter fullscreen mode Exit fullscreen mode

Top comments (0)