Changing the interval of SetInterval while it's running

后端 未结 16 1065
南旧
南旧 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: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);
    

提交回复
热议问题