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

JavaScript 防抖和节流的区别及实现 #37

Open
wengjq opened this issue Mar 11, 2018 · 0 comments
Open

JavaScript 防抖和节流的区别及实现 #37

wengjq opened this issue Mar 11, 2018 · 0 comments

Comments

@wengjq
Copy link
Owner

wengjq commented Mar 11, 2018

防抖的原理就是:尽管触发事件,但是一定在事件触发 n 秒后才执行,如果在一个事件触发的 n 秒内又触发了这个事件,那就以新的事件的时间为准,n 秒后才执行。总之,就是要等触发完事件 n 秒内不再触发事件。

function debounce (func, wait, immediate) {
    var timeout;

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

        if (timeout) clearTimeout(timeout);

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

节流的原理就是:如果持续触发事件,每隔一段时间,只执行一次事件。

function throttle(func, wait) {
    var context, args;
    var previous = 0;

    return function() {
        var now = +new Date();
        context = this;
        args = arguments;
        if (now - previous > wait) {
            func.apply(context, args);
            previous = now;
        }
    }
}


function throttle2(func, wait) {
    var context, args;
    var timeout;

    return function() {
        context = this;
        args = arguments;
        if (!timeout) {
            timeout = setTimeout(function() {
                timeout = null;
                func.apply(context, args)
            }, wait)
        }

    }
}
  • 第一种方法会立刻执行,第二种方法会在 n 秒后第一次执行。
  • 第一种方法停止触发后没有办法再执行事件,第二种方法停止触发后依然会再执行一次事件。

防抖和节流的区别

防抖是虽然事件持续触发,但只有等事件停止触发后 n 秒才执行函数,节流是持续触发的时候,每 n 秒执行一次函数。

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