PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

javascript函数节流和防抖的应用场景介绍

不言
不言 转载
2018-10-19 15:06:33 2436浏览

本篇文章给大家带来的内容是关于php变量作用域的用法介绍(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

throttle 节流

事件触发到结束后只执行一次。

应用场景

触发mousemove事件的时候, 如鼠标移动。

触发keyup事件的情况, 如搜索。

触发scroll事件的时候, 譬如鼠标向下滚动停止时触发加载数据。

coding

方法1  防抖

// function resizehandler(fn, delay){
//   clearTimeout(fn.timer);
//   fn.timer = setTimeout(() => {
//      fn();
//   }, delay);
// }
// window.onresize = () => resizehandler(fn, 1000);

方法2 闭包  防抖

function resizehandler(fn, delay){
    let timer = null;
    return function() {
      const context = this;
      const args=arguments;
      clearTimeout(timer);
      timer = setTimeout(() => {
         fn.apply(context,args);
      }, delay);
    }
 }
 window.onresize = resizehandler(fn, 1000);

debounce 防抖

事件出发后一定的事件内执行一次。

应用场景

window 变化触发resize事件是, 只执行一次。

电话号码输入的验证, 只需停止输入后进行一次。

coding

function resizehandler(fn, delay, duration) {
        let timer = null;
        let beginTime = +new Date();
        return function() {
          const context = this;
          const args = arguments;
          const currentTime = +new Date();
          timer && clearTimeout(timer);
          if ((currentTime - beginTime) >= duration) {
            fn.call(context, args);
            beginTime = currentTime;
           } else {
             timer = setTimeout(() => {
               fn.call(context, args)
             }, delay);
           }
        }
      }

        window.onresize = resizehandler(fn, 1000, 1000);

声明:本文转载于:segmentfault思否,如有侵犯,请联系admin@php.cn删除