DEV Community

Cover image for Timing Functions in JS?
_Khojiakbar_
_Khojiakbar_

Posted on • Edited 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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay