美文网首页
函数节流与函数防抖

函数节流与函数防抖

作者: 独爱一乐拉面 | 来源:发表于2017-05-22 21:20 被阅读0次

函数节流

适用场景:按钮防重复点击

/**
 * 函数节流  delay时间内,连续发起多个请求,只执行第一个请求
 * @param fun
 * @param delay
 * @returns {function()}
 */
const throttle = (fun, delay) => {
  let last = null;
  return (...cc) => {
    const now = + new Date();
    if (now - last > delay) {
      fun(...cc);
      last = now;
    }
  }
};

函数防抖

适用场景:input输入框搜索

/**
 * 函数防抖  delay时间内,连续发起多个请求,只执行最后一个请求
 * @params fun 需要防抖的方法
 * @params delay 毫秒数
 */
const debounce = (fun, delay) => {
  let timer = null;
  return (...cc) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fun(...cc);
    }, delay);
  }
};

相关文章

网友评论

      本文标题:函数节流与函数防抖

      本文链接:https://www.haomeiwen.com/subject/tvpixxtx.html