js防抖与节流注意点

68 阅读1分钟

防抖:

  • 1,注意this指向,如果没在防抖中使用this指向window
  • 2,注意event对象传递(...arg)
防抖:
function throttle(func, wait) {
    var timeout
    return function() {
         clearTimeout(timeout)
         timeout = setTimeout(function(){
                //this指向指回对应的绑定dom,...arg注意event对象传递,
                func.apply(this, ...args)
            }, wait)
    }
}

节流:

  • 1,时间戳方式,会立即执行
  • 2,定时器,不会立即执行
使用定时器的:
function throttle(func, wait) {
    var timeout;
    return function() {
        context = this;
        args = arguments;
        if (!timeout) {
            timeout = setTimeout(function(){
                timeout = null;
                func.apply(context, args)
            }, wait)
        }

    }
}