DEV Community

Arun
Arun

Posted on

Guide to setTimeout and setInterval in Javascript

The global object in Javascript provides two in-built methods setTimeout and setInterval to trigger a block of code at a scheduled time.

setInterval

setInterval method accepts two arguments. A callback function and delay in milliseconds. The function passed is called at specified intervals. setInterval will continue calling the passed function until we use another in-built method clearInterval or until the window is closed.

In this example, the increment function passed as callback, will be called after every one second.

let i = 0;
function increment() {
  i++;
  console.log(i);
}
setInterval(increment, 1000);
Enter fullscreen mode Exit fullscreen mode

setTimeout

setTimeout also accepts two arguements like setInterval. The function passed is called once after the specified interval.

After an interval of one second, the increment function passed to setTimeout will be called.

let i = 0;
function increment() {
  i++;
  console.log(i);
}
setTimeout(increment, 1000);
Enter fullscreen mode Exit fullscreen mode

clearInterval and clearTimeout

The setInterval and setTimeout functions returns a number which is used to identify that particular function. Calling clearInterval and clearTimeout by passing the corresponding id will stop executing it.

In the example shown below, clearInterval will be executed after 3 seconds, thus terminating the setInterval call.

let i = 0;
function increment() {
  i++;
  console.log(i);
}
const incrementTimer = setInterval(increment, 1000);
setInterval(() => {
  clearInterval(incrementTimer);
}, 3000)
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
topman14 profile image
Tope Akinkuade

In that last function, after incrementTimer has been cleared the first time, The second setInterval function will attempt to clear an interval that's already been cleared. Wouldn't it have been better to use a setTimeout Instead