防抖動處理和節流 小技巧

1. 簡單的防抖動處理,一秒內點擊一次

var timer = null;
$('.coupon').click(function(){
  if (timer) {
    return;
  }
  timer = true;
  setTimeout(function() {
    timer = false;
  }, 1000);

...

})

2. 向服務器請求數據

點擊按鈕向後臺請求數據 優化點:css

var running = false;
$('.btn').on('click', function() {
  if (running) {
    return;
  }
  running = true;

  $.ajax(url, {
    complete: () => {
      running = false;
    }
  })
});

另一些防抖動的小技巧,請參考:
http://blog.csdn.net/crystal6...
https://jinlong.github.io/201...git

3. 封裝好的簡單防抖動函數

// 防抖動函數 fn要執行的函數,timeout間隔毫秒數github

function debounce(fn, timeout) {
  let last = null;
  return function() {
    if (last) {
      return last.result;
    }

    setTimeout(() => { last = null; }, timeout || 1000);
    const result = fn.apply(this, arguments);
    last = { result };
    return result;
  };
}
//調用
btn.addEventListener('click', debounce(function() {
  ...
}, 1000));

4. 現成的工具庫Loadash

http://www.css88.com/doc/loda...
防抖動:
_.debounceajax

節流:
_.throttle服務器

相關文章
相關標籤/搜索