js setTimeout 防抖

        !function(){
            const $div = document.querySelector('#oDiv');
            let interval = 2000
            let t0 = new Date().getTime() + interval
            let tmr = null

            function updateTime(){
                let now = new Date().getTime()
                let span = Math.max(0, interval - (now - t0))
                t0 += interval

                $div.innerHTML = `${now} ${span}`
                
                tmr = setTimeout(() => {
                    updateTime()
                }, span);
            }
            updateTime()
        }()
/**
 * Self-adjusting interval to account for drifting
 * 
 * @param {function} workFunc  Callback containing the work to be done
 *                             for each interval
 * @param {int}      interval  Interval speed (in milliseconds) - This 
 * @param {function} errorFunc (Optional) Callback to run if the drift
 *                             exceeds interval
 */
function AdjustingInterval(workFunc, interval, errorFunc) {
    var that = this;
    var expected, timeout;
    this.interval = interval;

    this.start = function() {
        expected = Date.now() + this.interval;
        timeout = setTimeout(step, this.interval);
    }

    this.stop = function() {
        clearTimeout(timeout);
    }

    function step() {
        var drift = Date.now() - expected;
        if (drift > that.interval) {
            // You could have some default stuff here too...
            if (errorFunc) errorFunc();
        }
        workFunc();
        expected += that.interval;
        timeout = setTimeout(step, Math.max(0, that.interval-drift));
    }
}
原文地址:https://www.cnblogs.com/zh33gl/p/11660909.html