How to change setInterval delay programmatically?

Asked

Viewed 663 times

4

I tried this way but did not succeed. My intention is to make as an effect of the Bézier curve.

var count = 0;

var times = 100;
var fn = function() {
  count++;
  
  if(count === 25) {
    console.log(count, times);
    times = 1000;
  }
  if(count === 50) {
    console.log(count, times);
    clearInterval(interval);
  }
  
  document.getElementById('div').style.left = count + 'px';
}

var interval = setInterval(fn, times);
#div {
  background-color: black;
  height: 100px;
  width: 100px;
  position: relative;
  left: 0px;
}
<div id="div"></div>

2 answers

5


Once the setInterval consumes the arguments given to it and no longer checks them.

I suggest you use the setTimeout for so he will have to be called again each time times expire.

var count = 0;

var times = 100;
function periodical() {
  count++;
  
  if(count === 25) {
    console.log(count, times);
    times = 1000;
  }
  if(count === 50) {
    console.log(count, times);
    return;
  }
  
  document.getElementById('div').style.left = count + 'px';
  setTimeout(periodical, times);
}

setTimeout(periodical(), times);
#div {
  background-color: black;
  height: 100px;
  width: 100px;
  position: relative;
  left: 0px;
}
<div id="div"></div>

2

Sergio’s response fully meets the desired process. However, for clarification purposes to other users with a question that fully corresponds to the title of the question -

Maintain a reference at the Scheduler:

var myVar = setInterval(myTimer, 1000); // Um segundo (1000 ms) de intervalo

When you want to change the frequency, delete the Scheduler via clearInterval():

clearInterval(myVar);

Associate a new Scheduler to the reference:

myVar = setInterval(myTimer, 3000); // três segundos de intervalo

Browser other questions tagged

You are not signed in. Login or sign up in order to post.