zoukankan      html  css  js  c++  java
  • 节流 防抖

    //节流 设置的时间内只能调用一次
    //节流函数 写法1 时间差版本
    function
    throttle(method, delay) { let timer, args = arguments, start; return function fn() { let self = this; let now = Date.now(); if(!start){ start = now; } if(timer){ clearTimeout(timer); } if(now - start >= delay){ method.apply(self, args); start = now; }else { timer = setTimeout(function () { console.log(args,'args') fn.apply(self, args); }, delay); } } }

    //节流函数 写法2 定时器版本
    function throttle(fn,delay) {
        var executed = false
        return function () {
            if(executed) return;
            var that = this;
            
            fn.apply(that,...arguments)
            executed = true
            
            setTimeout(() => {
                executed = false;
            }, delay);
        }
    }
    // 防抖函数
    function
    debounce(method,delay){ let _delay = delay || 0; let timer = null; return function(){ let args = arguments; timer && clearTimeout(timer); timer = setTimeout(()=>{ method.apply(this,args) },_delay) } }

     这里用的apply和call主要改变this指向。

  • 相关阅读:
    googleMapReduce
    leveldb0
    大端模式和小端模式
    信号
    js中判断对象类型的几种方法
    js DOM之基础详解
    JavaScript作用域与闭包总结
    SCRIPT438: 对象不支持“trim”属性或方法
    JS合并多个数组去重算法
    js的 break 和 continue 计算问题
  • 原文地址:https://www.cnblogs.com/hill-foryou/p/11061224.html
Copyright © 2011-2022 走看看