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

函数节流与防抖是什么? #4

Open
rancho-xjq opened this issue Sep 27, 2021 · 0 comments
Open

函数节流与防抖是什么? #4

rancho-xjq opened this issue Sep 27, 2021 · 0 comments

Comments

@rancho-xjq
Copy link
Owner

简单的说 防抖是控制次数,节流是控制频率

  • 函数防抖

就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间

/**
 * @desc 函数防抖
 * @param func 函数
 * @param delay 延迟执行毫秒数
 * @param immediate true 表立即执行,false 表非立即执行
 */
function debounce(func, delay, immediate) {
    let timeout;
    return function() {
        let context = this;
        let args = argments;

        if (timeoue) clearTimeOut(timeout);
        if (immediate) {
            var callNow = !timeout
            timeout = setTimeout(() => {
                timeout = null;
            }, delay)
            if(callNow) fnc.apply(context, args);
        } else {
            timeout = setTimeout( function() {
                func.apply(context, args)
            }, delay)
        }
    }
}
  • 函数节流

所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数。让一个函数无法在很短的时间间隔内连续调用,而是间隔一段时间执行,这在我们为元素绑定一些事件的时候经常会用到,比如我们为 window 绑定了一个 resize 事件,如果用户一直改变窗口大小,就会一直触发这个事件处理函数,这对性能有很大影响。

/**
 * @desc 函数节流
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param type 1 表时间戳版,2 表定时器版
 */
 function throttle(func, wait ,type) {
     if(type===1){
         let previous = 0;
     }else if(type===2){
         let timeout;
     }
     return function() {
         let context = this;
         let args = arguments;
         if(type===1){
             let now = Date.now();

             if (now - previous > wait) {
                 func.apply(context, args);
                 previous = now;
             }
         }else if(type===2){
             if (!timeout) { 
                 timeout = setTimeout(() => {
                     timeout = null;
                     func.apply(context, args)
                 }, wait)
             }
         }
     }
 }

参考:
函数防抖和节流
JavaScript专题之跟着underscore学防抖
JavaScript专题之跟着 underscore 学节流

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

No branches or pull requests

1 participant