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防抖与节流 #4

Open
chenshuhong opened this issue Aug 23, 2019 · 1 comment
Open

JavaScript防抖与节流 #4

chenshuhong opened this issue Aug 23, 2019 · 1 comment
Labels

Comments

@chenshuhong
Copy link
Owner

chenshuhong commented Aug 23, 2019

防抖
触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间

function debounce(func,wait,immediate){
  var timeout,result
  var debounced =  function(){
    var context = this
    var args = arguments
    clearTimeout(timeout)
    if (immediate){
      var callNow = !timeout;
      timeout = setTimeout(function(){
        timeout = null;
      }, wait)
      if (callNow) result = func.apply(context, args)
    } else {
      timeout = setTimeout(function(){
        func.apply(context,args)
      },wait)
    }
    return result
  }
  
  debounced.cancel = function(){
    clearTimeout(timeout)
    timeout = null
  }
  
  return debounced
}

节流
高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率

/**
 * 双剑合璧版本
 * @param func
 * @param wait
 * @returns {Function}
 */
function throttle(func, wait,options = {}){
  var context, args,timeout,previous = 0,now;
  var throttled =  function(){
    context = this;
    args = arguments;
    //下次触发 func 剩余的时间
    now = +new Date()
    if (!previous && options.leading === false) previous = now;
    var remaining = wait - (now - previous);
    if (remaining<=0||remaining>wait){
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      previous = now;
      func.apply(context, args);
    }else if (!timeout&& options.trailing !== false) {
      timeout = setTimeout(function(){
        previous = options.leading === false ? 0 : new Date().getTime();
        timeout = null;
        func.apply(context, args)
      }, remaining);
    }
  }
  
  throttled.cancel = function() {
    clearTimeout(timeout);
    previous = 0;
    timeout = null;
  }
  
  return throttled
}
@chenshuhong
Copy link
Owner Author

动画中的防抖

function debounce(func) {
    var t;
    return function () {
        cancelAnimationFrame(t)
        t = requestAnimationFrame(func);
    }
}

@chenshuhong chenshuhong added the js label Aug 27, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant