debounce.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. let timeoutArr = [];
  2. /**
  3. * 防抖函数
  4. * 防抖原理:一定时间内,只有最后一次或第一次调用,回调函数才会执行
  5. * @param {Function} fn 要执行的回调函数
  6. * @param {Number} time 延时的时间
  7. * @param {Boolean} isImmediate 是否立即执行 默认true
  8. * @param {String} timeoutName 定时器ID
  9. * @return null
  10. vk.pubfn.debounce(function() {
  11. }, 1000);
  12. */
  13. function debounce(fn, time = 500, isImmediate = true, timeoutName = "default") {
  14. // 清除定时器
  15. if(!timeoutArr[timeoutName]) timeoutArr[timeoutName] = null;
  16. if (timeoutArr[timeoutName] !== null) clearTimeout(timeoutArr[timeoutName]);
  17. // 立即执行一次
  18. if (isImmediate) {
  19. var callNow = !timeoutArr[timeoutName];
  20. timeoutArr[timeoutName] = setTimeout(function() {
  21. timeoutArr[timeoutName] = null;
  22. }, time);
  23. if (callNow){
  24. if(typeof fn === 'function') fn();
  25. }
  26. } else {
  27. // 设置定时器,当最后一次操作后,timeout不会再被清除,所以在延时time毫秒后执行fn回调方法
  28. timeoutArr[timeoutName] = setTimeout(function() {
  29. if(typeof fn === 'function') fn();
  30. }, time);
  31. }
  32. }
  33. export default debounce