This question has already been answered:

I need to setInterval to change in time when I need to allow the program to change the duration of the intervals

Reported as a duplicate at Grundy. javascript Nov 2 '18 at 7:15 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

1 answer 1

Keep a variable with the time when the next triggering should occur. In setInterval() specify a very short period, for example. 1/5 second Inside to check whether the time of the next operation has come. No - we leave, there is - the payload of the function is executed and the next trigger time is set.

 var interval = 800, next, div = document.getElementById('tick'), slider=document.getElementById('slider'); slider.value = interval; slider.addEventListener( 'input', function(){ interval = parseInt( slider.value); }); function tack() { var now = (new Date).getTime(); if( next && next > now) return; next = now + interval; div.classList.toggle('black'); } window.setInterval( tack, 100); 
 #tick { width:20px;height:20px;border:1px solid #333; } .black { background-color:#333} 
 <div id="tick"></div> <input id="slider" type="range" min="200" max="1000"/>