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

JS函数防抖和函数节流 #13

Open
akeymo opened this issue Feb 12, 2020 · 0 comments
Open

JS函数防抖和函数节流 #13

akeymo opened this issue Feb 12, 2020 · 0 comments

Comments

@akeymo
Copy link
Owner

akeymo commented Feb 12, 2020

// 函数防抖
// 在事件被触发n秒后再执行回调函数,如果在这n秒内又被触发,则重新计时
function debounce(fn, wait) {
    let timer = null;
    return function (...args) {
        const context = this;
        // 如果存在timer,说明在n秒内又被触发了,则清空重新计时
        if (timer) {
            clearTimeout(timer);
            timer = null;
        }

        timer = setTimeout(() => {
            fn.apply(context, args);
        }, wait);
    }
}

// 函数节流(定时器方式)
// 在单位时间内,无论多少次触发事件,都只执行一次回调函数
function throttleBySetTimeout(fn, wait) {
    let timer = null;
    return function (...args) {
        const context = this;
        if (!timer) {
            timer = setTimeout(() => {
                timer = null;
                return result = fn.apply(context, args);
            }, wait);
        }
    }
}

// 函数节流(时间戳)
function throttleByGapTime(fn, wait) {
    let prevTime = 0;

    return function (...args) {
        const context = this;
        const nowTime = +new Date();
        if (nowTime - prevTime > wait) {
            prevTime = nowTime;
            return result = fn.apply(context, args);
        }
    }
}

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