Search code examples
javascriptloopssettimeout

setTimeout inside loop run code 1 time then wait and repeat


wanting to know if there is a better way to do this or a way to limit the size into a function

let timerOut = false;
if (!timerOut) {
  //do code
  timerOut = true;
  setTimeout(function () {
    timerOut = false;
  }, 6000);
}   

i need it so if x is true it will do something and wait for set time then if x is still true repeat

this runs in a setInterval


setInterval(() => {
  console.log(x);
  tick()
}, 1000);

var x = true;

function tick() {
  if (x) {
    let timerOut = false;
    if (!timerOut) {
      x = false
      timerOut = true;
      setTimeout(function() {
        x = true;
        timerOut = false;
      }, 6000);
    }
  }
}

x would not be in the setTimeout that is just to make it loop x would be change by other factors


let x = setInterval(() => {
  console.log("hi")
  clearInterval(x)
}, 3000)

^answer


Solution

  • You can use setInterval which returns the 'id' of the interval.

    If you store that id, you can delete that interval whenever you want.

    let x = setInterval(()=>{console.log("hi")}, 3000)

    clearInterval(x) //deletes that interval