What is the difference between setTimeout() and setInterval() in JavaScript?


setTimeout() function

setTimeout( function, duration) − This function calls function after duration milliseconds from now. This goes for one execution. Let’s see an example −

It waits for 2000 milliseconds, and then runs the callback function alert(‘Hello’) −

setTimeout(function() { alert('Hello');}, 2000);

setInterval() function

setInterval(function, duration) − This function calls function after every duration milliseconds. This goes for unlimited times. Let’s see an example −

It triggers the alert(‘Hello’) after every 2000 milliseconds, not only once.

setInterval(function() { alert('Hello');}, 2000);

Updated on: 24-Nov-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements