一、防抖

1.定义实现

当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。

  1. const debounce = (fn, wait) => {
  2. let timer = null;
  3. return (...args) => {
  4. if (timer) {
  5. clearTimeout(timer);
  6. }
  7. timer = setTimeout(() => {
  8. fn.apply(this, args);
  9. }, wait);
  10. };
  11. };

2.测试代码:

  1. <!DOCTYPE html>
  2. <html lang="zh-cmn-Hans">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta http-equiv="x-ua-compatible" content="IE=edge, chrome=1" />
  6. <title>debounce</title>
  7. <style>
  8. #container {
  9. width: 100%;
  10. height: 200px;
  11. line-height: 200px;
  12. text-align: center;
  13. color: #fff;
  14. background-color: #444;
  15. font-size: 30px;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <div id="container"></div>
  21. <script>
  22. const debounce = (fn, wait) => {
  23. let timer = null;
  24. return (...args) => {
  25. if (timer) {
  26. clearTimeout(timer);
  27. }
  28. timer = setTimeout(() => {
  29. fn.apply(this, args);
  30. }, wait);
  31. };
  32. };
  33. var count = 1;
  34. var container = document.getElementById("container");
  35. function getUserAction(e) {
  36. console.log(e);
  37. container.innerHTML = count++;
  38. }
  39. container.onmousemove = debounce(getUserAction, 1000);
  40. </script>
  41. </body>
  42. </html>

二、节流

1.定义实现

在规定时间内,保证执行一次该函数

  1. const throttle = (fn, wait) => {
  2. let last = 0;
  3. return (...args) => {
  4. let now = +new Date();
  5. if (now - last >= wait) {
  6. last = now;
  7. fn.apply(this, args);
  8. }
  9. };
  10. };
  11. // or
  12. const throttle = (func, wait) => {
  13. var timeout;
  14. return (...args) => {
  15. if (!timeout) {
  16. timeout = setTimeout(function () {
  17. timeout = null;
  18. func.apply(this, args);
  19. }, wait);
  20. }
  21. };
  22. };

2.实现

  1. <!DOCTYPE html>
  2. <html lang="zh-cmn-Hans">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta http-equiv="x-ua-compatible" content="IE=edge, chrome=1" />
  6. <title>throttle</title>
  7. <style>
  8. #container {
  9. width: 100%;
  10. height: 200px;
  11. line-height: 200px;
  12. text-align: center;
  13. color: #fff;
  14. background-color: #444;
  15. font-size: 30px;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <div id="container"></div>
  21. <script>
  22. const throttle = (fn, wait) => {
  23. let last = 0;
  24. return (...args) => {
  25. let now = +new Date();
  26. if (now - last >= wait) {
  27. last = now;
  28. fn.apply(this, args);
  29. }
  30. };
  31. };
  32. var count = 1;
  33. var container = document.getElementById("container");
  34. function getUserAction(e) {
  35. console.log(e);
  36. container.innerHTML = count++;
  37. }
  38. container.onmousemove = debounce(getUserAction, 1000);
  39. </script>
  40. </body>
  41. </html>