What is setTimeout and setInterval in JavaScript?
setTimeout
and setInterval
are two functions in JavaScript that allow you to schedule a piece of code to be executed after a specified amount of time has passed.
setTimeout
is a function that executes a function or specified piece of code only once after the specified time interval has passed. The syntax for using setTimeout
is as follows:
setTimeout(function, delay);
Where function
is the function to be executed after the specified time interval and delay
is the time interval in milliseconds. For example:
setTimeout(function() {
console.log("Hello, World!");
}, 3000); // This will log "Hello, World!" to the console after 3 seconds (3000 milliseconds).
setInterval
is similar to setTimeout
, but it executes the function repeatedly at the specified interval until clearInterval
is called or the page is unloaded. The syntax for using setInterval
is as follows:
setInterval(function, interval);
Where function
is the function to be executed repeatedly and interval
is the time interval in milliseconds. For example:
let intervalID = setInterval(function() {
console.log("Hello, World!");
}, 3000); // This will log "Hello, World!" to the console every 3 seconds (3000 milliseconds).
// To stop the interval, you can call clearInterval as follows:
clearInterval(intervalID);
It is important to keep in mind that both setTimeout
and setInterval
are non-blocking, meaning they do not block further execution of the script while they are waiting for the time interval to pass.