JavaScript setInterval() Method: Live Counter & Digital Clock Examples

In the ever-changing world of web development, asynchronous activities are a must. Timing and scheduling operations are crucial when it comes to updating real-time data, polling servers for fresh information, or producing interactive animations. The setInterval() function excels in this situation.

JavaScript setInterval() Method

JavaScript setInterval() method is used to repeatedly run a function or a section of code at predetermined intervals (measured in milliseconds). Until the window is closed or the clearInterval() function is performed, this method keeps calling the procedure.

Syntax:

setInterval(function, milliseconds);

Parameters:

  • function – a function containing a block of code
  • milliseconds – the time interval between the execution of the function

How setInterval() Method Works

Since JavaScript is single-threaded, its code is executed by a single thread. For activities like managing timing events brought on by setTimeout() and setInterval(), browsers often employ a separate thread for their timer implementation. When you invoke these functions, the browser’s 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”. 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.

Display a Text Message Every One Second Using setInterval()

The setInterval() is a built-in JavaScript function employed to repetitively execute a specified function or code snippet at predetermined intervals.

Code:

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

setInterval(greet, 1000);

In this instance, it’s set to invoke the greet() function every 1000 milliseconds (1 second). Consequently, the string ‘Hello world’ is logged to the console each second until the program concludes or the interval is explicitly halted when the window is closed.

Output:

Output of setInterval() Method Example

Building a Live Counter Using setInterval()

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. The setInterval() function in JavaScript is typically utilized for this objective. We can develop a dynamic and engaging user experience by scheduling the periodic execution of code to update the counter value at set intervals by setInterval().

Code:

<!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>

Live Counter

The updateCounter() method is used in this example to update the text content of an element with the id “counter” and display the current count by incrementing a counter variable (count). The setInterval() function makes this updating process happen once per second, creating a live counter that increments in value automatically without any input from the user.

Output:

Output of Live Counter

Programming a Digital Clock Using setInterval()

Digital clocks are crucial in a variety of digital platforms since they provide users with up-to-date information and thus improve their experience. This functionality is usually implemented using the setInterval() method of JavaScript, which allows developers to update the clock display at specified time intervals.

Code:

<!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>

Digital Clock


The updateClock() function retrieves 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 identified by the id ‘clock’.

Output:

Output of Digital Clock

How to Clear setInterval() Intervals

A built-in JavaScript method called clearInterval() is used to end the interval that was established by setInterval(). It accepts a single parameter, the identifier that the setInterval() method returned when it was first invoked. The function or code block that is supplied is stopped from being executed again when clearInterval() is called, therefore ending the interval.

Code:

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); 

In this script, 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 with the interval to cease the interval, followed by logging a message. Consequently, the interval persists until the count attains the value of 5, upon which it halts automatically.

Output:

Output of Clear setInterval() Intervals

Application of setInterval() Method

  • Animations: Using the setInterval() method, an element’s location, size, or colour may be changed regularly on a webpage.
  • Real-time data updates: The setInterval() method may be used to routinely get data from a server or API and refresh the UI.
  • 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.

Conclusion

JavaScript¬†setInterval() function may be used to continually run a function or code block at predetermined intervals. It’s indispensable for jobs like updating user interface components, retrieving data from servers or making animations that call for recurring updates or operations. Misuse or too frequent pauses, however, might have a detrimental effect on performance. Therefore, to maintain maximum application performance, setInterval() must be used sparingly, taking into account performance consequences and making sure that thorough cleanup with clearInterval() is carried out when intervals are no longer needed.

Continue Reading:

Reference

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

Anurag Pandey
Anurag Pandey
Articles: 20