函数防抖 节流

采用debounce(防抖)和throttle(节流)的方式来减少调用频率,同时又不影响实际效果。

函数防抖:将几次操作合并为一此操作进行。原理是维护一个计时器,规定在delay时间后触发函数,但是在delay时间内再次触发的话,就会取消之前的计时器而重新设置。这样一来,只有最后一次操作能被触发。

function debounce(fn, wait) {   
    var timeout = null;   
    return function() {       
        if(timeout !== null) clearTimeout(timeout);       
        timeout = setTimeout(fn, wait);   
    }
}
// 处理函数
function handle() {   
    console.log(Math.random());
}
// 滚动事件
window.addEventListener('scroll', debounce(handle, 1000));

函数节流:使得一定时间内只触发一次函数。原理是通过判断是否到达一定时间来触发函数。

var throttle = function(func, delay) {           
    var prev = Date.now();           
    return function() {               
        var context = this;               
        var args = arguments;               
        var now = Date.now();               
        if (now - prev >= delay) {                   
            func.apply(context, args);                   
            prev = Date.now();               
        }           
    }       
}       
function handle() {           
    console.log(Math.random());       
}       
window.addEventListener('scroll', throttle(handle, 1000))

区别: 函数节流不管事件触发有多频繁,都会保证在规定时间内一定会执行一次真正的事件处理函数,而函数防抖只是在最后一次事件后才触发一次函数。

   比如在页面的无限加载场景下,我们需要用户在滚动页面时,每隔一段时间发一次 Ajax 请求,而不是在用户停下滚动页面操作时才去请求数据。这样的场景,就适合用节流技术来实现。

猜你喜欢

转载自www.cnblogs.com/anbozhu7/p/11250183.html