美文网首页
函数防抖debounce、节流函数throttle

函数防抖debounce、节流函数throttle

作者: liuniansilence | 来源:发表于2019-03-18 16:49 被阅读0次
// 防抖
function debounce(fn, delay, ctx) {
    let sto = null;
    return function(){
        let args = arguments;
        sto && clearTimeout(sto);
        sto = setTimeout(() => {
            fn.apply(ctx, args);
        }, delay);
    }
}

// 节流
function throttle(fn, delay, ctx) {
    let flag = true;
    return function(){
        let args = arguments;
        if(flag) {
            fn.apply(ctx, args);
            flag = false;
            setTimeout(function() {
                flag = true;
            }, delay)
        }
    }
}

window.onresize = throttle(function() {
    console.log('test')
}, 1000, this)

相关文章

网友评论

      本文标题:函数防抖debounce、节流函数throttle

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