Mastering setInterval and clearInterval in JavaScript for Timing Events

SetInterval

The JavaScript setInterval() function repeatedly executes a specified function at a fixed time interval (in milliseconds) until it is stopped with clearInterval().

Understanding the setInterval Function in JavaScript

The setInterval() function is commonly used for tasks like running a loop every second, updating HTML elements, handling timing events, or creating animations. Unlike setTimeout(), which runs only once, setInterval continues to run continuously at the delay you specify, making it ideal for real-time updates such as counters, clocks, or fetching data from web APIs.

Syntax & Parameters of setInterval

The setInterval() is a global function so it can be called directly anywhere in a program using the below syntax:

setInterval(function, milliseconds, params);

Parameters:

  • function – a function containing a block of code
  • milliseconds – the numeric parameter that defines the delay in milliseconds between each execution of the function
  • params – optional parameters to pass to the function

Return:

This method returns the ID of the timer which is a numeric value and can be used later to cancel the timer by passing it as a parameter to the clearInterval() method.

How Browser Timing Events Work with setInterval

Since JavaScript is single-threaded, its code runs on a single thread, and for managing timing events like creating a loop or handling repeated iterations, we rely on methods such as setTimeout() and setInterval().

When you invoke these functions, the browser timer system typically operates independently from the main JavaScript execution thread. Upon timer expiration, the associated callback function is not immediately placed on the execution stack. Instead, it’s added to a queue known as the “task queue” or “callback queue”. The JavaScript engine operates an event loop that continuously checks whether the execution stack is empty. If it is, the event loop moves tasks from the task queue to the execution stack, executing them one by one. Therefore, when a timer expires, the callback function is placed in the task queue and waits for the execution stack to empty before being processed by the event loop.

Examples of setTimeout in Programming

Example 1: Displaying a Text Message Every Second

Let’s see how we can display a text message every second using this method.

function greet() {
    console.log('Hello world');
}

setInterval(greet, 1000);

In this example, the greet() function is set to invoke every 1000 milliseconds (1 second). As a result, the string ‘Hello world’ is logged to the console every 1 second until the program ends or the window is closed.

JavaScript setInterval Method

Example 2: Creating a Live Counter

Updating a live counter is a typical situation in web development where the visible value in the counter changes continuously with no input from the user.

Using setInterval() function is good for this objective. We can create a dynamic user experience by scheduling the periodic execution of code to update the counter value at set intervals.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Live Counter</title>
</head>
<body>
<div id="counter">0</div>

<script>
let count = 0;
const counterElement = document.getElementById('counter');

function updateCounter() {
    count++;
    counterElement.textContent = count;
}

// Update the counter every second
const intervalId = setInterval(updateCounter, 1000);
</script>
</body>
</html>

The updateCounter() function updates the text content of the HTML element with the id ‘counter’ by incrementing a variable, stored in a const declaration, so the counter increases automatically every second.

Output of Live Counter

Example 3: Creating a Digital Clock

Digital clocks are crucial in a variety of digital platforms. For creating this, we can use the setInterval() method and update the clock per second.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Digital Clock</title>
</head>
<body>
<div id="clock"></div>

<script>
function updateClock() {
    const clockElement = document.getElementById('clock');
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const seconds = now.getSeconds().toString().padStart(2, '0');
    clockElement.textContent = `${hours}:${minutes}:${seconds}`;
}

updateClock();

const intervalId = setInterval(updateClock, 1000);
</script>
</body>
</html>

The updateClock() function gets the current time and formats it into hours, minutes, and seconds. It is invoked immediately upon page load to update the clock. Additionally, setInterval(updateClock, 1000) ensures that updateClock() is called every 1000 milliseconds (1 second), guaranteeing consistent clock updates. The time is displayed within a <div> element having the id ‘clock’.

Output of Digital Clock

clearInterval Function: Stopping Execution Loops

Another built-in JavaScript method called clearInterval() is used to stop a repeating function call, allowing developers to add control logic such as attaching it to a button that halts the interval.

In short, clearInterval() is used to end the interval set by setInterval().

The clearInterval() method accepts a single parameter, the identifier or ID that the setInterval() method returned when it was first invoked. The function given in setInterval() is stopped from being executed again when clearInterval() is called, thereby ending the interval.

let count = 0;

function printCount() {
    console.log('Count:', count);
    count++;
    if (count >= 5) {
        clearInterval(intervalId);
        console.log('Interval stopped after 5 counts');
    }
}

const intervalId = setInterval(printCount, 1000); 

Here the printCount() function logs the current value of the count to the console and increments it. Utilizing setInterval(), printCount() is called every 1000 milliseconds (1 second). Within printCount(), a check is performed to see if the count has reached 5. If this condition is met, clearInterval() is invoked to stop the interval, followed by logging a message.

JavaScript clearInterval Method

Application of setInterval Method

  • Animations: In JavaScript programming, the setInterval() method can be used to move elements, update arrays of values, or even trigger an alert at regular intervals on a webpage.
  • Real-time data updates: The setInterval() method can specify refresh cycles to fetch data from web APIs, and developers often combine it with libraries like jQuery to update the UI smoothly.
  • Timer countdowns: A timer countdown that is shown on a webpage at regular intervals can be made smaller until it approaches 0 by using the setInterval() function.
  • Games: You may move objects, check for collisions, and continuously update the game state by using the setInterval() method.
  • Automatic slide shows: setInterval() may be used to generate automatic slide shows on a webpage by recurrently altering the displayed picture after a predefined interval.

Cross-Language Notes

While the setInterval function is standard for JavaScript, similar timing features exist in C#, Python, TypeScript, etc, where code can run continuously at a fixed interval. If you are learning using W3Schools or other references, you will often see examples where a function is triggered every few seconds to demonstrate timing.

Final Notes on setInterval and clearInterval

The JavaScript setInterval function is a powerful tool for handling timing events in web programming. It executes a function call at a fixed interval, measured in milliseconds, and continues to run continuously until stopped with the clearInterval method. Unlike setTimeout, which executes a function only once, setInterval is used for repeated iteration such as updating counters, animations, or refreshing data from web APIs.

Developers can specify parameters to control execution logic and use different declarations like var, let, or const for variables. For example, a string message can be sent to the console every second, or an array of values can be updated on the fly. Common use cases include running a digital clock, triggering an alert, or automating UI changes in HTML with libraries such as jQuery.

In practice, the setInterval method offers flexibility but must be used carefully. Poorly managed loops or frequent executions can degrade performance. Whether working in plain JavaScript, TypeScript, or even looking at examples in C#, the same principles apply: use clear logic, manage your timers, and stop them with clearInterval when they are no longer needed.

Related Tutorials:

Reference

https://developer.mozilla.org/en-US/docs/Web/API/setInterval

Review Your Cart
0
Add Coupon Code
Subtotal