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

手写防抖和节流 #10

Open
wweggplant opened this issue Sep 25, 2023 · 0 comments
Open

手写防抖和节流 #10

wweggplant opened this issue Sep 25, 2023 · 0 comments

Comments

@wweggplant
Copy link
Owner

防抖和节流

防抖是持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。节流是指当持续触发事件时,保证一定时间段内只调用一次事件处理函数.

防抖

防抖要考虑是有:

  1. this指向
  2. 传入的参数
  3. 立即执行情况的处理
function debounce(func, wait, immediate) {
    var timeout, result
    return function() {
        var context = this
        var args = arguments;
        if(timeout) {
            clearTimeout(timeout)
        }
        if (immediate) {
            var canImmediate = !timeout
            timeout = setTimeout(function() {
                timeout = null
            }, wait)
            if (canImmediate) {
                result = func.apply(context, args) // 立即执行的函数有返回值需要在最后返回
            }
        } else {
           timeout = setTimeout(function () {
                func.apply(context, args)
            }, wait) 
        }
        return result
    }
}

节流

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

    var later = function() {
        previous = +new Date();
        timeout = null;
        func.apply(context, args)
    };

    var throttled = function() {
        var now = +new Date();
        //下次触发 func 剩余的时间
        var remaining = wait - (now - previous);
        context = this;
        args = arguments;
         // 如果没有剩余的时间了或者你改了系统时间
        if (remaining <= 0 || remaining > wait) {
            if (timeout) {
                clearTimeout(timeout);
                timeout = null;
            }
            previous = now;
            func.apply(context, args);
        } else if (!timeout) {
            timeout = setTimeout(later, remaining);
        }
    };
    return throttled;
}
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