In JavaScript, time-based events refer to actions or functions that are triggered after a certain period of time has elapsed, or at specific intervals.
There are four time based events. The four time-based events are: setTimeout()
, setInterval()
, clearTimeout()
, and clearInterval()
.
The setTimeout function is used to execute a function or a code block after a specific delay in milliseconds and other hand setInterval function is used to repeatedly execute a function or a code block at a specific interval in milliseconds.
//syntax of setTimeout
function myCallback(){
console.log("printing after 2000 millisec/2sec.");
}
setTimeout(myCallback, 2000);
//syntax of setInterval
function myCallback(){
console.log("printing repeatedly after 2000 millisec/2sec.");
}
setInterval(myCallback, 2000);
We use clearTimeout()
if we need to cancel a scheduled timeout before it occurs, and clearInterval()
is used when we need to execute a function up to a certain point and then terminate it..
JavaScript timers like setTimeout()
and setInterval()
are frequently used to create animations and visual effects on websites. For example, sliding banners, fading effects, or progress bars and also used in form handling.