HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Timing Events

JavaScript allows you to execute code at specific time intervals. These are called timing events. Using the window object methods, you can delay code execution or repeat a task over and over with a set time gap.


Timing Demonstration

Interact with the live examples below to see timeouts and intervals in action:

Live Digital Clock

Updates every 1 second (setInterval)

00:00:00
Delayed Greeting

Trigger after 3 seconds (setTimeout)

Inactive

The setTimeout() Method

The setTimeout() method executes a function, after waiting a specified number of milliseconds.

// Executes alert after 3000ms (3 seconds)
setTimeout(function() {
    alert("Time is up!");
}, 3000);

Stopping a Timeout

The clearTimeout() method stops the execution of the function specified in setTimeout(). You must save the timeout ID to a variable first.

let myTimeout = setTimeout(myFunction, 2000);

// Stop the execution
clearTimeout(myTimeout);

The setInterval() Method

The setInterval() method repeats a given function at every given time-interval.

// Executes myFunction every 1 second
let myInterval = setInterval(myFunction, 1000);

function myFunction() {
    console.log("Tick!");
}

Stopping an Interval

The clearInterval() method stops the executions of the function specified in the setInterval() method.

let timer = setInterval(countSeconds, 1000);

// Later, stop the timer
clearInterval(timer);
Tip: 1 second = 1,000 milliseconds. If you want a 5-second delay, use 5000.

Timing Methods Summary

Method Description Execution
setTimeout() Delays code execution Runs Once
setInterval() Repeats code execution Runs Repeatedly
clearTimeout() Cancels a pending timeout -
clearInterval() Cancels an active interval -
Important: Timing methods are asynchronous. This means JavaScript continues executing the rest of your code while the timer is running in the background.

Key Points to Remember

  • Timing events belong to the window object.
  • setTimeout is for one-time delays.
  • setInterval is for recurring tasks (animations, clocks, etc.).
  • Always store the timer ID in a variable if you need to STOP it later.
  • The delay value is always in milliseconds.
  • Small intervals (under 10ms) may be throttled by browsers to preserve battery life.