阿富

web前端

导航

【事件】函数的防抖与节流

/*
 *
 * 防抖
 *
 */
var debouncer = function(func, time, delay) {
    time = time || 300;
    delay = typeof delay === 'boolean' ? delay : true;
    var id, run = true;
    if (delay) {
        return function() {
            if (id) clearTimeout(id);
            id = setTimeout(function(args) {
                func.apply(this, args);
            }.bind(this, arguments), time);
        };
    } else {
        return function() {
            if (id) clearTimeout(id);
            id = setTimeout(function() {
                run = true;
            }, time);
            if (run) {
                run = false;
                func.apply(this, arguments);
            }
        };
    }
};

//使用情况
window.addEventListener('resize', debouncer(function(e) {
    console.log('300ms间隔,立即执行');
}, 300, false));

window.addEventListener('resize', debouncer(function(e) {
    console.log('300ms间隔,最后执行');
}, 300, true));

input.addEventListener('keyup', debouncer(function(e) {
    console.log('1000ms间隔,最后执行');
}, 1000, true));



/*
 *
 * 节流
 *
 */
var throttle = function(func, time) {
    time = time || 300;
    var run = true;
    return function() {
        if (run) {
            run = false;
            setTimeout(function() {
                run = true;
            }, time);
            func.apply(this, arguments);
        }
    };
};

//使用情况
window.addEventListener('scroll', throttle(function(e) {
    console.log(e);
}, 300));

 

posted on 2016-07-14 22:06  阿富  阅读(138)  评论(0)    收藏  举报