statice.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // 防抖
  2. export const debounce = (fn, delay) => {
  3. var time = null
  4. return function() {
  5. let context = this;//记录一下this指向
  6. let args = arguments;
  7. //清除定时任务
  8. if (time) clearTimeout(time);
  9. time = setTimeout(function() {
  10. time = null;
  11. fn.apply(context, args)
  12. }, delay)
  13. }
  14. }
  15. //节流
  16. export const throttle=(fn, delay) => {
  17. // 时间戳
  18. var timeTwo = 0 //new Date();
  19. // 定时器
  20. var timeThree = null;
  21. return function() {
  22. let context = this;
  23. let args = arguments;
  24. var now = new Date()
  25. // !!!!时间戳实现【new Date()虽然获取结果不是时间戳但是计算结果会自动转化为时间戳】
  26. // if(now-timeTwo>=delay){
  27. // fn.apply(context,args);
  28. // timeTwo=new Date();
  29. // }
  30. // !!!!定时器实现
  31. // if (!timeThree) {
  32. // timeThree = setTimeout(function () {
  33. // fn.apply(context, args);
  34. // timeThree=null;
  35. // }, delay)
  36. // }
  37. // 结合 ps:最后一次触发在固定频率内会在延迟后触发
  38. var wait = delay - (now - timeTwo)
  39. clearTimeout(timeThree)
  40. if (wait <= 0) {
  41. fn.apply(context, args);
  42. timeTwo = new Date();
  43. } else {
  44. timeThree = setTimeout(function() {
  45. fn.apply(context, args);
  46. }, delay)
  47. }
  48. }
  49. }