Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

throttle vs debounce #31

Open
msforest opened this issue Oct 22, 2018 · 2 comments
Open

throttle vs debounce #31

msforest opened this issue Oct 22, 2018 · 2 comments

Comments

@msforest
Copy link
Owner

msforest commented Oct 22, 2018

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

  • debouncing, executes the function if there was no new event in $wait milliseconds
  • throttle, in case of a "storm of events", this executes once every $threshold

我理解的意思是:

  • throttle,函数节流,每隔一定时间内执行一次event。
  • debounce,函数去抖,在一定时间内,若event不再触发,就在wait时间之后执行指定function。

可以参考特效

@msforest
Copy link
Owner Author

msforest commented Mar 9, 2019

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
Copy link
Owner Author

function debounce(fn, wait){
    var timeid;
    return () => {
        clearTimeout(timeid);
        timeid = setTimeout(() => {
            timeid = null;
            fn.applay(this, argument);
        }, wait)
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant