zoukankan      html  css  js  c++  java
  • 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));
        }
    }
    
  • 相关阅读:
    HashMap 的数据结构
    JVM的内存区域划分
    分库分表的基本思想
    分表与分库使用场景以及设计方式
    千万数据的分库分表(一)
    用c++实现快速排序和归并排序
    如何查看python版本号?
    python的正则表达式
    python3的队列,比python2更好
    markdown如何插入代码?
  • 原文地址:https://www.cnblogs.com/zh33gl/p/11660909.html
Copyright © 2011-2022 走看看