Changing the interval of SetInterval while it's running

后端 未结 16 1042
南旧
南旧 2020-11-22 07:35

I have written a javascript function that uses setInterval to manipulate a string every tenth of a second for a certain number of iterations.

function timer(         


        
相关标签:
16条回答
  • 2020-11-22 08:06

    I'm a beginner in javascript, and didn't found any help in the previous answers (but many good ideas).
    This piece of code below accelerates (acceleration > 1) or decelerates (acceleration <1). I hope it might help some people:

    function accelerate(yourfunction, timer, refresh, acceleration) {
        var new_timer = timer / acceleration;
        var refresh_init = refresh;//save this user defined value
        if (refresh < new_timer ){//avoid reseting the interval before it has produced anything.
            refresh = new_timer + 1 ;
        };
        var lastInter = setInterval(yourfunction, new_timer);
        console.log("timer:", new_timer);
        function stopLastInter() {
            clearInterval(lastInter);
            accelerate(yourfunction, new_timer, refresh_init, acceleration);
            console.log("refresh:", refresh);
        };
        setTimeout(stopLastInter, refresh);
    }
    

    With :

    • timer: the setInterval initial value in ms (increasing or decreasing)
    • refresh: the time before a new value of timer is calculated. This is the step lenght
    • factor: the gap between the old and the next timer value. This is the step height
    0 讨论(0)
  • 2020-11-22 08:07

    I had the same question as the original poster, did this as a solution. Not sure how efficient this is ....

    interval = 5000; // initial condition
    var run = setInterval(request , interval); // start setInterval as "run"
    
        function request() { 
    
            console.log(interval); // firebug or chrome log
            clearInterval(run); // stop the setInterval()
    
             // dynamically change the run interval
            if(interval>200 ){
              interval = interval*.8;
            }else{
              interval = interval*1.2;
            }
    
            run = setInterval(request, interval); // start the setInterval()
    
        }
    
    0 讨论(0)
  • 2020-11-22 08:07
    var counter = 15;
    var interval = setTimeout(function(){
        // your interval code here
        window.counter = dynamicValue;
        interval();
    }, counter);
    
    0 讨论(0)
  • 2020-11-22 08:10

    Inspired by the internal callback above, i made a function to fire a callback at fractions of minutes. If timeout is set to intervals like 6 000, 15 000, 30 000, 60 000 it will continuously adapt the intervals in sync to the exact transition to the next minute of your system clock.

    //Interval timer to trigger on even minute intervals
    function setIntervalSynced(callback, intervalMs) {
    
        //Calculate time to next modulus timer event
        var betterInterval = function () {
            var d = new Date();
            var millis = (d.getMinutes() * 60 + d.getSeconds()) * 1000 + d.getMilliseconds();
            return intervalMs - millis % intervalMs;
        };
    
        //Internal callback
        var internalCallback = function () {
            return function () {
                setTimeout(internalCallback, betterInterval());
                callback();
            }
        }();
    
        //Initial call to start internal callback
        setTimeout(internalCallback, betterInterval());
    };
    
    0 讨论(0)
  • 2020-11-22 08:11

    Use setTimeout() instead. The callback would then be responsible for firing the next timeout, at which point you can increase or otherwise manipulate the timing.

    EDIT

    Here's a generic function you can use to apply a "decelerating" timeout for ANY function call.

    function setDeceleratingTimeout(callback, factor, times)
    {
        var internalCallback = function(tick, counter) {
            return function() {
                if (--tick >= 0) {
                    window.setTimeout(internalCallback, ++counter * factor);
                    callback();
                }
            }
        }(times, 0);
    
        window.setTimeout(internalCallback, factor);
    };
    
    // console.log() requires firebug    
    setDeceleratingTimeout(function(){ console.log('hi'); }, 10, 10);
    setDeceleratingTimeout(function(){ console.log('bye'); }, 100, 10);
    
    0 讨论(0)
  • 2020-11-22 08:11

    You could use an anonymous function:

    var counter = 10;
    var myFunction = function(){
        clearInterval(interval);
        counter *= 10;
        interval = setInterval(myFunction, counter);
    }
    var interval = setInterval(myFunction, counter);
    

    UPDATE: As suggested by A. Wolff, use setTimeout to avoid the need for clearInterval.

    var counter = 10;
    var myFunction = function() {
        counter *= 10;
        setTimeout(myFunction, counter);
    }
    setTimeout(myFunction, counter);
    
    0 讨论(0)
提交回复
热议问题