DEV Community

Velcruza
Velcruza

Posted on

Using setInterval() in Javascript

In my last project I wanted to set production per second and have my "factories" produce resources on a set time interval. Unfortunately I did not have enough time to figure out then so I decided to go back and look into how to use setInterval() in Javascript.

setInterval() repeatedly calls a function with a fixed time delay between each call. So you can utilize to do something like I mentioned above (producing x amount of resources every x seconds) or for animations! You can use it in a way to have your picture move from one position to the other every x amount of seconds (hint hint... you might maybe see this in our upcoming project).

Let's get into how to use setInterval() in your code now.

setInterval() takes in a callback function and a delay in milliseconds. The method returns an interval ID so you can remove it later by calling clearInterval().

basic example of the syntax:

let intervalId = setInterval(callBackFn, 1000)

function callBackFn(){
   console.log("This message will log every one second")
}
Enter fullscreen mode Exit fullscreen mode

This example would log "This message will log every one second" to the console every one second.

Here is an example of using the clearInterval() method with setInterval() to be able to start/stop the function from executing every x seconds:

let nIntervId;

function changeColor() {
  // check if already an interval has been set up
  if (!nIntervId) {
    nIntervId = setInterval(flashText, 1000);
  }
}

function flashText() {
  const oElem = document.getElementById("my_box");
  if (oElem.className === "go") {
    oElem.className = "stop";
  } else {
    oElem.className = "go";
  }
}

function stopTextColor() {
  clearInterval(nIntervId);
  // release our intervalID from the variable
  nIntervId = null; 
}

document.getElementById("start").addEventListener("click", changeColor);
document.getElementById("stop").addEventListener("click", stopTextColor);
Enter fullscreen mode Exit fullscreen mode

Things to be careful of when using the setInterval() method:
-If you're using it to manipulate data from a fetch request you have to keep in mind that the fetch request itself takes sometime
-Using it to setState can also get really funky (which is what happened with my project, therefore didn't end up using it)

Top comments (0)