函数防抖

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

  1. function debounce(fn, wait) {
  2. var timeout = null; //定义一个定时器
  3. return function() {
  4. if(timeout !== null)
  5. clearTimeout(timeout); //清除这个定时器
  6. timeout = setTimeout(fn, wait);
  7. }
  8. }
  9. // 处理函数
  10. function handle() {
  11. console.log(Math.random());
  12. }
  13. // 滚动事件
  14. window.addEventListener('scroll', debounce(handle, 1000));

函数节流

指连续触发事件但是在 n 秒中只执行一次函数。
函数节流用于onresize,onscroll等段时间内会多次触发事件。

  1. var throttle = function(func, delay) {
  2. var timer = null;
  3. var startTime = Date.now(); //设置开始时间
  4. return function() {
  5. var curTime = Date.now();
  6. var remaining = delay - (curTime - startTime); //剩余时间
  7. var context = this;
  8. var args = arguments;
  9. clearTimeout(timer);
  10. if (remaining <= 0) { // 第一次触发立即执行
  11. func.apply(context, args);
  12. startTime = Date.now();
  13. } else {
  14. timer = setTimeout(func, remaining); //取消当前计数器并计算新的remaining
  15. }
  16. }
  17. }
  18. function handle() {
  19. console.log(Math.random());
  20. }
  21. window.addEventListener('scroll', throttle(handle, 1000));