Changing the interval of SetInterval while it's running

后端 未结 16 1273
南旧
南旧 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:00

    Here is yet another way to create a decelerating/accelerating interval timer. The interval gets multiplied by a factor until a total time is exceeded.

    function setChangingInterval(callback, startInterval, factor, totalTime) {
        let remainingTime = totalTime;
        let interval = startInterval;
    
        const internalTimer = () => {
            remainingTime -= interval ;
            interval *= factor;
            if (remainingTime >= 0) {
                setTimeout(internalTimer, interval);
                callback();
            }
        };
        internalTimer();
    }
    

提交回复
热议问题