DEV Community

Cover image for Timing Functions in JS?
_Khojiakbar_
_Khojiakbar_

Posted on

Timing Functions in JS?

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

  1. setTimeout: Schedules a one-time execution of a function after a specified delay.
  2. clearTimeout: Cancels a setTimeout if it hasn't already executed.
  3. setInterval: Schedules repeated execution of a function at specified intervals.
  4. clearInterval: Cancels a setInterval 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);
Enter fullscreen mode Exit fullscreen mode

How They Work Together

  1. setTimeout schedules a message to be printed after 5 seconds but is canceled with clearTimeout before it can execute.
  2. setInterval schedules a message to be printed every 2 seconds.
  3. After 10 seconds, clearInterval stops the repeated messages from setInterval.

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)