JavaScript Timers

JavaScript timers allow you to execute code after a specified delay or repeatedly at scheduled intervals. They are useful for displaying notifications, creating countdowns, updating clocks, scheduling animations, and performing periodic tasks.

JavaScript provides four commonly used timer functions: setTimeout(), setInterval(), clearTimeout(), and clearInterval().

The setTimeout() function schedules code to run once after a delay, while setInterval() schedules code to run repeatedly. The clearTimeout() and clearInterval() functions cancel their corresponding scheduled timers.

In this tutorial, you will learn how each timer function works, how to cancel timers, and how to use them in practical JavaScript examples.

setTimeout() in JavaScript

The setTimeout() function schedules a callback function to execute once after a specified delay.

It is useful when you want to display a message after a few seconds, hide a notification automatically, or delay an action.

Syntax

setTimeout(callback, delay);

The parameters are:

  • callback: The function to execute after the delay.
  • delay: The minimum delay in milliseconds before the callback becomes eligible to run.

One second equals 1,000 milliseconds. For example, 2000 represents two seconds.

Example of setTimeout()

console.log("Start");

setTimeout(function () {
  console.log("This message appears after 2 seconds");
}, 2000);

console.log("End");

Output:

Start
End
This message appears after 2 seconds

The setTimeout() function schedules the callback and allows the remaining synchronous code to continue. The callback runs later, after the delay has elapsed and JavaScript can execute it.

The specified delay is not an exact guarantee. If the browser is busy or the page is in the background, the callback may run later than expected.

Using setTimeout() with an Arrow Function

You can use an arrow function instead of a regular function.

setTimeout(() => {
  console.log("Welcome to JavaScript!");
}, 3000);

After approximately three seconds, the console displays:

Welcome to JavaScript!

Example: Displaying a Delayed Message

<button id="showButton">Show Message</button>
<p id="message"></p>

<script>
  const button = document.getElementById("showButton");
  const message = document.getElementById("message");

  button.addEventListener("click", function () {
    message.textContent = "Please wait...";

    setTimeout(function () {
      message.textContent = "Your message is ready!";
    }, 2000);
  });
</script>

When the user clicks the button, the page displays Please wait.... After approximately two seconds, the message changes to Your message is ready!.

This technique is useful for delayed notifications and simple user-interface effects.

setInterval() in JavaScript

The setInterval() function schedules a callback to execute repeatedly at a specified interval until the interval is canceled.

It is useful for updating clocks, refreshing displayed information, running simple counters, and performing periodic tasks.

Syntax

setInterval(callback, delay);

The parameters are:

  • callback: The function to execute repeatedly.
  • delay: The requested interval between scheduled executions, measured in milliseconds.

Example of setInterval()

setInterval(function () {
  console.log("This message repeats every second");
}, 1000);

The console displays the message repeatedly, approximately once per second under normal conditions.

The interval continues running until it is canceled or the relevant execution environment ends.

Example: Creating a Counter

<p>Count: <span id="counter">0</span></p>

<script>
  let count = 0;

  const counter = document.getElementById("counter");

  setInterval(function () {
    count++;
    counter.textContent = count;
  }, 1000);
</script>

The counter increases by one approximately every second.

For example, the displayed values progress through 1, 2, 3, and so on.

Because this interval is never canceled, it continues running while the page and execution context remain active. In a real application, you may want to stop the timer when it is no longer needed.

Example: Displaying the Current Time

<p id="clock"></p>

<script>
  const clock = document.getElementById("clock");

  function updateClock() {
    clock.textContent = new Date().toLocaleTimeString();
  }

  updateClock();

  setInterval(updateClock, 1000);
</script>

The page displays the current local time and updates it approximately every second.

Calling updateClock() before creating the interval displays the time immediately instead of waiting for the first interval callback.

clearTimeout() in JavaScript

The clearTimeout() function cancels a timeout that has been scheduled with setTimeout().

It is useful when an action should no longer happen, such as canceling a delayed notification or stopping a scheduled operation after a user changes their mind.

Syntax

clearTimeout(timeoutId);

The timeoutId is the identifier returned by setTimeout().

Example of clearTimeout()

const timeoutId = setTimeout(function () {
  console.log("This message will not appear");
}, 3000);

clearTimeout(timeoutId);

console.log("Timeout canceled");

Output:

Timeout canceled

The timeout is canceled before its callback executes, so the delayed message is not displayed.

Example: Canceling a Delayed Action

<button id="startButton">Start Timer</button>
<button id="cancelButton">Cancel Timer</button>

<p id="status"></p>

<script>
  let timeoutId;

  const startButton = document.getElementById("startButton");
  const cancelButton = document.getElementById("cancelButton");
  const status = document.getElementById("status");

  startButton.addEventListener("click", function () {
    clearTimeout(timeoutId);

    status.textContent = "Waiting...";

    timeoutId = setTimeout(function () {
      status.textContent = "Timer completed!";
    }, 5000);
  });

  cancelButton.addEventListener("click", function () {
    clearTimeout(timeoutId);
    status.textContent = "Timer canceled.";
  });
</script>

When the user clicks Start Timer, a five-second timeout is scheduled. Clicking Cancel Timer cancels the pending timeout and displays a cancellation message.

Starting the timer again also cancels the previous timeout, preventing multiple pending timers from being created by repeated clicks.

clearInterval() in JavaScript

The clearInterval() function cancels a repeating interval created by setInterval().

It is useful when you want to stop a counter, pause periodic updates, or end a repeating task after a condition is met.

Syntax

clearInterval(intervalId);

The intervalId is the identifier returned by setInterval().

Example of clearInterval()

let count = 0;

const intervalId = setInterval(function () {
  count++;

  console.log(count);

  if (count === 5) {
    clearInterval(intervalId);
    console.log("Interval stopped");
  }
}, 1000);

Output:

1
2
3
4
5
Interval stopped

The interval runs approximately once per second. When the counter reaches five, clearInterval() cancels the repeating timer.

The callback that is already executing is allowed to finish. Canceling the interval prevents future scheduled executions.

Example: Start and Stop a Counter

<p>Count: <span id="count">0</span></p>

<button id="start">Start</button>
<button id="stop">Stop</button>

<script>
  let count = 0;
  let intervalId = null;

  const output = document.getElementById("count");
  const startButton = document.getElementById("start");
  const stopButton = document.getElementById("stop");

  startButton.addEventListener("click", function () {
    if (intervalId !== null) {
      return;
    }

    intervalId = setInterval(function () {
      count++;
      output.textContent = count;
    }, 1000);
  });

  stopButton.addEventListener("click", function () {
    clearInterval(intervalId);
    intervalId = null;
  });
</script>

Clicking Start begins the counter, and clicking Stop cancels the interval.

The intervalId !== null check prevents repeated clicks on Start from creating multiple intervals. Setting the identifier to null after cancellation allows the counter to be started again.

Difference Between setTimeout() and setInterval()

Both functions schedule callbacks, but they behave differently.

FeaturesetTimeout()setInterval()
ExecutionSchedules a callback onceSchedules repeated callbacks
TimingRuns after a specified delayRepeats at a requested interval
CancellationclearTimeout()clearInterval()
Common useDelayed messages and one-time actionsCounters, clocks, and periodic updates
RepetitionDoes not repeat automaticallyRepeats until canceled

Example Comparing Both Functions

setTimeout(function () {
  console.log("Runs once");
}, 1000);

setInterval(function () {
  console.log("Repeats");
}, 1000);

The first callback runs once after approximately one second. The second callback runs repeatedly at roughly one-second intervals until its interval is canceled.

The example intentionally leaves the interval running. In an actual application, save its identifier and cancel it when it is no longer needed.

Difference Between clearTimeout() and clearInterval()

These functions cancel different kinds of scheduled timers.

FeatureclearTimeout()clearInterval()
PurposeCancels a scheduled timeoutCancels a repeating interval
Used withsetTimeout()setInterval()
ArgumentTimeout identifierInterval identifier
Main effectPrevents a pending timeout callback from runningPrevents future interval callbacks from being scheduled

Browsers generally use numeric timer identifiers, while other JavaScript environments may use different identifier types. In either case, use the identifier returned by the timer function.

Although browser timer IDs can technically be passed to either clearing function, using the matching function makes your code clearer and easier to maintain.

Using setTimeout() to Create a Countdown

Timers can also be used to create a simple countdown.

<p id="countdown">5</p>

<script>
  let count = 5;

  const output = document.getElementById("countdown");

  const intervalId = setInterval(function () {
    count--;
    output.textContent = count;

    if (count <= 0) {
      clearInterval(intervalId);
      output.textContent = "Time is up!";
    }
  }, 1000);
</script>

The countdown starts at five and decreases approximately once per second. When it reaches zero, the interval stops and the page displays Time is up!.

This example uses setInterval() because the countdown updates repeatedly. For precise countdown timing, calculate the remaining time from a target timestamp instead of assuming every interval callback occurs exactly one second apart.

Important Things to Know About JavaScript Timers

Timer Delays Are Not Exact

The delay passed to setTimeout() or setInterval() specifies when a callback becomes eligible to run, not an exact execution time. Busy JavaScript execution, browser scheduling, and background-tab throttling can delay callbacks.

Timers Do Not Make Long Calculations Asynchronous

Wrapping a long calculation in setTimeout() does not automatically make the calculation run in parallel. The callback still runs on the JavaScript thread when scheduled.

Avoid Creating Unnecessary Intervals

Unmanaged intervals can continue running longer than needed. Store the returned identifier and call clearInterval() when the task is finished or the associated component is no longer active.

Use Recursive setTimeout() When Appropriate

If each operation must finish before the next delay is scheduled, a recursive setTimeout() can be more suitable than setInterval().

function runTask() {
  console.log("Task executed");

  setTimeout(runTask, 2000);
}

runTask();

This example schedules the next run only after the current callback finishes. It continues indefinitely until you add a condition or cancellation mechanism to stop it.

Frequently Asked Questions

What is setTimeout() in JavaScript?

setTimeout() schedules a callback to execute once after a specified delay. The callback may run later than the requested delay if the runtime is busy.

What is setInterval() in JavaScript?

setInterval() schedules a callback to run repeatedly at a specified interval until the timer is canceled.

What is clearTimeout() used for?

clearTimeout() cancels a pending timeout created by setTimeout() using its returned identifier.

What is clearInterval() used for?

clearInterval() cancels a repeating interval created by setInterval() and prevents future scheduled executions.

What is the difference between setTimeout() and setInterval()?

setTimeout() schedules a callback once, while setInterval() schedules callbacks repeatedly until canceled.

Are JavaScript timers exact?

No. Timer delays are approximate. The runtime schedules callbacks when the requested delay has elapsed, but other work and browser throttling can delay execution.

Can setInterval() be stopped?

Yes. Save the identifier returned by setInterval() and pass it to clearInterval() when the repeating task should stop.

Conclusion

JavaScript timers help you schedule delayed and repeating actions. The setTimeout() function runs a callback once after a delay, while setInterval() schedules repeated callbacks. Their corresponding cancellation functions, clearTimeout() and clearInterval(), help prevent unwanted execution.

Understanding these four functions will help you create countdowns, clocks, notifications, counters, and other time-based interactions. Use timers carefully, remember that their timing is not exact, and cancel them when they are no longer needed.