All the following functions(setTimeout, clearTimeout, setInterval, clearInterval) are part of JavaScript's timing functions. These functions are used to schedule the execution of code at specific times or intervals.
Summary of Timing Functions
-
setTimeout
: Schedules a one-time execution of a function after a specified delay. -
clearTimeout
: Cancels asetTimeout
if it hasn't already executed. -
setInterval
: Schedules repeated execution of a function at specified intervals. -
clearInterval
: Cancels asetInterval
to stop the repeated execution.
Usage Example Combining All Timing Functions
Here's a combined example using all these timing functions in a single script:
// Schedule a one-time function with setTimeout
let snackTimeout = setTimeout(() => {
console.log("Time for a snack!");
}, 5000);
// Schedule a repeated function with setInterval
let reminderInterval = setInterval(() => {
console.log("Don't forget to drink water!");
}, 2000);
// Cancel the snack timeout before it executes
clearTimeout(snackTimeout);
// Cancel the reminder interval after 10 seconds
setTimeout(() => {
clearInterval(reminderInterval);
console.log("Stopping the water reminders.");
}, 10000);
How They Work Together
-
setTimeout
schedules a message to be printed after 5 seconds but is canceled withclearTimeout
before it can execute. -
setInterval
schedules a message to be printed every 2 seconds. - After 10 seconds,
clearInterval
stops the repeated messages fromsetInterval
.
Word to Call All These Functions
You can refer to these functions collectively as timing functions
or timer functions
in JavaScript. They are essential tools for managing time-based events in web development.
Top comments (0)