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

    “函数防抖”的关键在于:在一个动作发生一定事件之后,才执行特定的事件。

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
    7. <title>Document</title>
    8. <style>
    9. #content {
    10. width: 200px;
    11. height: 200px;
    12. background-color: gray;
    13. margin: 100px;
    14. color: black;
    15. padding: 50px;
    16. font-size: 56px;
    17. }
    18. </style>
    19. </head>
    20. <body>
    21. <div id="content">
    22. </div>
    23. <script>
    24. var num = 0;
    25. var content = document.getElementById("content");
    26. var changeNum = function(){
    27. num++;
    28. content.innerHTML = num;
    29. }
    30. var debounce = function(func, delay){
    31. var timer;
    32. return function(...args){
    33. if (timer) {
    34. clearTimeout(timer);
    35. }
    36. // 第一版
    37. // timer = setTimeout(function(){
    38. // // timeout的this是window,但实际上应该是content元素
    39. // func();
    40. // }, delay);
    41. // 第二版,使用箭头函数的特性
    42. // 箭头函数没有this作用域,他的this来自作用域链,也没有arguments
    43. timer = setTimeout(() => {
    44. console.log(this);
    45. func(...args);
    46. }, delay);
    47. };
    48. };
    49. content.onmouseover = debounce(changeNum, 500);
    50. </script>
    51. </body>
    52. </html>

    函数节流(throttle):
    当持续触发事件时,保证一定时间段内只调用一次事件处理函数。

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
    7. <title>Document</title>
    8. </head>
    9. <body>
    10. <button id="btn1">点击</button>
    11. <script>
    12. let btn1 = document.getElementById('btn1');
    13. let fn = () => {
    14. console.log('我被点击了');
    15. };
    16. let throttle = function(func, delay) {
    17. var flag = true;
    18. return function(...args){
    19. if(!flag) {
    20. return;
    21. }
    22. flag = false;
    23. setTimeout(()=>{
    24. func(args);
    25. flag = true;
    26. },delay);
    27. };
    28. };
    29. btn1.onclick = throttle(fn, 2000);
    30. </script>
    31. </body>
    32. </html>

    有可以使用时间戳来实现。