msforest / notebook

好记性不如烂笔头,记录知识的点点滴滴。
https://github.com/msforest/notebook/wiki
0 stars 0 forks source link

throttle vs debounce #31

Open msforest opened 5 years ago

msforest commented 5 years ago

这两个概念一直都理不清楚,看过不少关于区分概念的文章,如JavaScript 函数节流和函数去抖应用场景辨析这篇文章,还是稀里糊涂滴:joy:,直到看到一句简单的英文句子才理解:

我理解的意思是:

可以参考特效

msforest commented 5 years ago
function throttle(fn, interval) {
    var timer, first = true;
    return function() {
        if (first) {
            fn.apply(this, arguments);
            return first = false;
        }
        if (timer) {return false;}
        timer = setTimeout(() => {
            clearTimeout(timer);
            timer = null;
            fn.apply(this, arguments);
        }, interval);
    }
}
msforest commented 5 years ago
function debounce(fn, wait){
    var timeid;
    return () => {
        clearTimeout(timeid);
        timeid = setTimeout(() => {
            timeid = null;
            fn.applay(this, argument);
        }, wait)
    }
}