• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / JavaScript / setInterval JavaScript – How to Repeat Code in Set Time Intervals

setInterval JavaScript – How to Repeat Code in Set Time Intervals

March 3, 2022 Leave a Comment

The setInterval() method in JavaScript will run a function or code in a set time interval that you can choose.

setInterval(function(){
  //Code that will run every 1000 milliseconds
}, 1000);

In the code above, the setInterval() method will run the function in it’s first parameter every 1000 milliseconds, or 1 second. We can change that parameter to be however often we want to execute the function call.

The code will loop forever in the set time interval unless it is cleared using the clearInterval() method.

A lot of the time, we will see an if conditional statement if the code above. Usually once a certain condition is met, we then will want to end the setInterval() method. We can do this by setting a variable to the setInterval method, var interval = setInterval() and then clearing it by using the clearInterval() method. We will see an example of this below.


To see how the setInterval() method in JavaScript works, let’s create a simple example. Here is code that will run a simple countdown timer.

Let’s start with the simple HTML setup:

<div id="div1">
  <div id="click-me" onclick="startCountdown()">Start Countdown</div>
  <div id="countdown-text"></div>
</div>

Below will be the JavaScript code to make this countdown timer work.

var counterStartTime = 6;
var interval = setInterval(function(){
  counterStartTime--;
  document.getElementById("countdown-text").innerHTML = "<b>" + counterStartTime + "</b>";
  if( counterStartTime == 0 ){
    clearInterval(interval);
    alert("5 seconds have passed.");
  }
}, 1000);

The basic overview of this code is that the setInterval() method will run a function that will display a number every second. The number will start at 5, and then when it gets to 0, an alert box will be fired stating that “5 seconds have passed”.

We will then stop the setInterval() method from running the function again by using the clearInterval() method. The code clearInterval(interval); will clear the timer set by the setInterval() method.

To view this example in action, take a look at the last example in this post.

Let’s take a look at another example below.

setInterval() in Action Using JavaScript

In this example, we will have a div with a background color. We will change the background color of the div every second. We will provide the user with a button to stop the changing of the color.

Here is the simple HTML setup:

<style>#div2 { width:300px; height: 200px; background: #7bbfa2; }</style>
<div id="div1">
  <div id="div2"></div>
  <div id="click-me" onclick="stopBackground()">Stop Background Color Change</div>
</div>

In the JavaScript code, we will have a setInterval() method that will run a function every 1000 milliseconds, or 1 second. In the function, we will generate a random color with some JavaScript code. We will then change the background color of #div2 using the backgroundColor property.

We will then use an onclick event to run a stopBackground() function we create when the user clicks a button. This function will simply clear the timer of the setInterval() method we created. We do this by using the clearInterval() method.

Here is the JavaScript code:

var interval = setInterval(function(){
  //Create a random color
  var randomColor = "#" + (Math.floor(Math.random()*16777215).toString(16));
  
  //Set the background of #div2 to this color
  document.getElementById("div2").style.backgroundColor = randomColor;
}, 1000);

//Our function to clear the setInterval() method above
function stopBackground(){
  clearInterval(interval);
}

The final code and output for this example of using the setInterval() method in JavaScript is below:

Code Output:

Stop Background Color Change

Full Code:

<style>#div2 { width:300px; height: 200px; background: #7bbfa2; }</style>
<div id="div1">
  <div id="div2"></div>
  <div id="click-me" onclick="stopBackground()">Stop Background Color Change</div>
</div>

<script>

var interval = setInterval(function(){
  var randomColor = "#" + (Math.floor(Math.random()*16777215).toString(16));
  document.getElementById("div2").style.backgroundColor = randomColor;
}, 1000);

function stopBackground(){
  clearInterval(interval);
}

</script>

Hopefully this article has been useful for you to understand how the setInterval() method in JavaScript works.

Other Articles You'll Also Like:

  • 1.  How to Remove All Numbers From String in JavaScript
  • 2.  Using JavaScript to Add to Array
  • 3.  Using JavaScript to Round to 4 Decimal Places
  • 4.  Using JavaScript to Check if Variable is a String
  • 5.  Using JavaScript to Count Even Numbers in an Array
  • 6.  Using JavaScript to Get Radio Button Value
  • 7.  Using JavaScript to Change the Image src
  • 8.  Using JavaScript to Get the Page Title
  • 9.  JavaScript if else Shorthand Statement
  • 10.  How to Use JavaScript to Round Up Numbers

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy