JavaScript > Browser APIs > Timers > setInterval()

Displaying a Counter with setInterval()

This code snippet demonstrates how to use setInterval() to create a simple counter that updates every second and displays it on the webpage.

Code Snippet

This HTML page contains a heading to display the counter. The JavaScript code initializes a counter variable count to 0. The updateCounter function increments the counter and updates the content of the HTML element with the id 'counter'. The setInterval function calls updateCounter every 1000 milliseconds (1 second). The returned intervalId is stored so that the interval can be cleared later using clearInterval. The setTimeout function is used to stop the counter after 10 seconds. This is optional, but it demonstrates how to clear an interval.

// HTML (index.html)
<!DOCTYPE html>
<html>
<head>
  <title>setInterval() Counter</title>
</head>
<body>
  <h1>Counter: <span id="counter">0</span></h1>
  <script>
    let count = 0;

    // Function to update the counter
    function updateCounter() {
      count++;
      document.getElementById('counter').textContent = count;
    }

    // Set interval to call updateCounter every 1000 milliseconds (1 second)
    const intervalId = setInterval(updateCounter, 1000);

    // Stop the counter after 10 seconds (optional)
    setTimeout(() => {
      clearInterval(intervalId);
      console.log('Counter stopped!');
    }, 10000);
  </script>
</body>
</html>

Concepts Behind the Snippet

The core concepts behind this snippet are setInterval(), clearInterval(), and the Document Object Model (DOM). setInterval() repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. clearInterval() cancels a repeating action which was set up using the setInterval() method. The DOM allows JavaScript to interact with and manipulate HTML elements.

Real-Life Use Case

setInterval() is commonly used to create animations, update dashboards with real-time data, implement countdown timers, or automatically refresh content on a webpage.

Best Practices

Always store the return value of setInterval() in a variable so that you can later clear the interval using clearInterval(). Failing to do so can lead to memory leaks and performance issues. Consider using requestAnimationFrame for animations for smoother rendering.

Interview Tip

Be prepared to discuss the differences between setInterval() and setTimeout(). setInterval() repeatedly executes a function, while setTimeout() executes a function only once after a specified delay. Also, explain the importance of using clearInterval() to prevent memory leaks.

When to Use Them

Use setInterval() when you need to perform an action repeatedly at a fixed interval. For example, polling a server for updates, updating a clock, or creating a recurring notification.

Memory Footprint

setInterval() can have a significant memory footprint if the interval is very short or if the function being called is resource-intensive. Make sure to clear the interval when it is no longer needed to avoid memory leaks.

Alternatives

setTimeout() can be used to simulate setInterval() by recursively calling itself at the end of the timeout. requestAnimationFrame() is a better choice for animations as it synchronizes updates with the browser's refresh rate. WebSockets can be used for real-time data updates, which are more efficient than polling with setInterval().

Pros

Simple to use for creating recurring tasks. Well-supported across all browsers.

Cons

Can lead to performance issues if not used carefully. May cause the function to be called more frequently than intended if the function takes longer to execute than the specified interval. Requires manual clearing to prevent memory leaks.

FAQ

  • What happens if the function passed to setInterval() takes longer to execute than the specified interval?

    If the function takes longer to execute than the interval, subsequent calls to the function may overlap or be delayed, potentially leading to unexpected behavior and performance issues. Consider using setTimeout() recursively or other alternatives in these situations.
  • How do I stop a setInterval() timer?

    You can stop a setInterval() timer by calling clearInterval() and passing the ID returned by setInterval() as an argument.