节流函数

  • 当某个函数被非常频繁地触发,但它期间只少数地几次,限制两次执行的时间间隔不能太短,从而实现性能优化,这样的函数称为节流函数,一般用在窗口缩放、滚动监听等。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    function throttle(action, wait = 1000) {
    let time = Date.now();
    return function() {
    if ((time + wait - Date.now()) < 0) {
    action();
    time = Date.now();
    }
    }
    }