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: 2023-11-24T00:58:53+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements