Changing the interval of SetInterval while it's running

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

提交回复
热议问题