利用闭包实现函数防抖、函数节流

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_39181833/article/details/81437119
function _throttle(fn, delay) {
  var canRun = true;
  return function() {
    if (!canRun) {
      return false;
    }
    canRun = false;
    fn.apply(this, Array.from(arguments));
    setTimeout(() => {
      canRun = true;
    }, delay);
  };
}
function _deBounce(fn, delay) {
  var timer = null;
  return function() {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.call(this, ...arguments);
    }, delay);
  };
}
var object = {
  a: 666,
};
var fn = function(num) {
  console.log(this.a);
  console.log(num);
};
// var process_fun = _throttle(fn, 2000);
// setInterval(() => process_fun.call(object, 1), 10);

var process_fun = _deBounce(fn, 200);
var timer = setInterval(() => process_fun.call(object, 1), 10);
setTimeout(() => {
  clearTimeout(timer);
}, 2000);
process_fun();

 

展开阅读全文

没有更多推荐了,返回首页