How to change the delay of the setInterval programmatically?

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>
    
asked by anonymous 01.12.2015 / 20:32

2 answers

5

Once started, setInterval consumes the arguments that have been passed to it and no longer checks them.

I suggest you use setTimeout so it will have to be called again every time a times expires.

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>
    
01.12.2015 / 20:38
2

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

Keep a reference to 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 with the reference:

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