js节流,防抖

首先说一下什么是节流,什么是防抖.

节流:顾名思义 就是节省流量  限制一个函数在一定时间内只能执行一次。

  前端开发过程中,有一些事件或者函数,会被频繁地触发(短时间按内多次触发),最常见的例如,onresize,scroll,mousemove ,mousehover 等,这些事件的触发频率很高,不做限制的话,有可能一秒之内执行几十次、几百次,如果在这些函数内部执行了其他函数,尤其是执行了操作 DOM 的函数(浏览器操作 DOM 是很耗费性能的),那不仅会造成计算机资源的浪费,还会降低程序运行速度,甚至造成浏览器卡死、崩溃。这种问题显然是致命的。

  除此之外,重复的 ajax 调用不仅可能会造成请求数据的混乱,还会造成网络拥塞,占用服务器带宽,增加服务器压力,显然这个问题也是需要解决的。

写法:  使用setTimeout方法

  var timer = null;
  function throttle(fn,wait){
    return function(hello){
        var context = this;
        var args = arguments;
        if(!timer){
            timer = setTimeout(function(){
                fn.apply(context,args);
                timer = null;
            },wait)
        }
    }()
}
    
function handle(){
    console.log(Math.random());
} 
$('#jl').on('click',throttle(handle,2000))

什么是防抖?

  短时间内多次触发同一事件,只执行最后一次,或者只执行最开始的一次,中间的不执行。

    var timer = null;
function throttle(fn,wait){return function(hello){
        var context = this;
        var args = arguments;
        if(timer) clearTimeout(timer)
        timer = setTimeout(function(){
                fn.apply(context,args);
                timer = null;
            },wait)
    }()
}
    
function handle(){
    console.log(Math.random());
} 
$('#jl').on('click',throttle(handle,2000))

其实两个方法都是差不多的,只是一个是隔一段时间执行,一个只执行最后一次

原文地址:https://www.cnblogs.com/wgs-blog/p/14776982.html