事件防抖:在用户连续触发事件过程中,不能执行代码。

    1. //防抖debounce代码:
    2. function debounce(fn) {
    3. let timeout = null; // 创建一个标记用来存放定时器的返回值
    4. return function () {
    5. // 每当用户输入的时候把前一个 setTimeout clear 掉
    6. clearTimeout(timeout);
    7. // 然后又创建一个新的 setTimeout,
    8. //这样就能保证interval 间隔内如果时间持续触发,就不会执行 fn 函数
    9. timeout = setTimeout(() => {
    10. fn.apply(this, arguments);
    11. }, 500);
    12. };
    13. }
    14. // 处理函数
    15. function handle() {
    16. console.log(Math.random());
    17. }
    18. // 滚动事件
    19. window.addEventListener('scroll', debounce(handle));

    事件节流:设置一个时间间隔,时间间隔内只允许执行一次。

    1. //节流throttle代码:
    2. function throttle(fn) {
    3. let canRun = true; // 通过闭包保存一个标记
    4. return function () {
    5. // 在函数开头判断标记是否为true,不为true则return
    6. if (!canRun) return;
    7. // 立即设置为false
    8. canRun = false;
    9. // 将外部传入的函数的执行放在setTimeout中
    10. setTimeout(() => {
    11. // 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。
    12. // 当定时器没有执行的时候标记永远是false,在开头被return掉
    13. fn.apply(this, arguments);
    14. canRun = true;
    15. }, 500);
    16. };
    17. }
    18. function sayHi(e) {
    19. console.log(e.target.innerWidth, e.target.innerHeight);
    20. }
    21. window.addEventListener('resize', throttle(sayHi));