手写一个防抖

2020-04-28  本文已影响0人  huanghaodong
function debounce(func, wait, immediate) {

    var timeout, result;

    var debounced = function () {
        var context = this;
        var args = arguments;

        if (timeout) clearTimeout(timeout);
        if (immediate) {
            timeout = setTimeout(function(){
                timeout = null;
            }, wait)
            if (!timeout) result = func.apply(context, args)
        }
        else {
            timeout = setTimeout(function(){
                func.apply(context, args)
            }, wait);
        }
        return result;
    };

    debounced.cancel = function() {
        clearTimeout(timeout);
        timeout = null;
    };

    return debounced;
}
上一篇 下一篇

猜你喜欢

热点阅读