1. const button = document.getElementById('btn_1')
    2. function payMoney() {
    3. console.log('支付成功')
    4. }
    5. function debounce(func, delay) {
    6. // 先定义,才可以清除,定义到外围是因为所以独立执行的函数都能通过闭包的形式对timer这个变量进行操作
    7. let timer = null
    8. // 使用高阶函数的原因防止定义时就执行
    9. return function() {
    10. // 如果不保存this,那么因为回调的原因运行时已经在window下了
    11. let context = this
    12. let args = arguments
    13. if (timer) {
    14. // 正在计时中,并且再次触发相同事件,所以要取消计时并且重新开始计时
    15. clearTimeout(timer)
    16. }
    17. timer = setTimeout(function () {
    18. func.apply(context, args)
    19. }, delay)
    20. }
    21. }
    22. button.addEventListener('click', debounce(payMoney, 1000))
    23. function coloring() {
    24. let r = Math.floor(Math.random() * 255)
    25. let g = Math.floor(Math.random() * 255)
    26. let b = Math.floor(Math.random() * 255)
    27. document.body.style.background = `rgb(${r}, ${g}, ${b})`
    28. }
    29. function throttle(func, delay) {
    30. let timer
    31. return function() {
    32. let context = this
    33. let args = arguments
    34. if (timer) {
    35. // 如果timer被赋值了,那就不执行任务直接返回
    36. return
    37. }
    38. // 如果timer没有被赋值或者任务已经执行完了,就位timer赋值进行延迟执行
    39. timer = setTimeout(function() {
    40. func.apply(context, args)
    41. // 不使用clearTimeout(),是因为这个清空行为是在延迟执行任务以后发生的
    42. timer = null
    43. }, delay)
    44. }
    45. }
    46. window.addEventListener('resize', throttle(coloring, 2000))

    防抖简版:

    1. function debounce(func, delay) {
    2. let timer
    3. return (...args) => {
    4. if (timer) {
    5. // 正在计时中,并且再次触发相同事件,所以要取消计时并且重新开始计时
    6. clearTimeout(timer)
    7. }
    8. timer = setTimeout(() => {
    9. func.apply(this, args)
    10. }, delay)
    11. }
    12. }

    节流简版:

    1. function throttle(func, delay) {
    2. let timer
    3. return (...args) => {
    4. if (timer) {
    5. // 如果timer被赋值了,那就不执行任务直接返回
    6. return
    7. }
    8. // 如果timer没有被赋值或者任务已经执行完了,就为timer赋值进行延迟执行
    9. timer = setTimeout(() => {
    10. func.apply(this, args)
    11. // 不使用clearTimeout(),是因为这个清空行为是在延迟执行任务以后发生的
    12. timer = null
    13. }, delay)
    14. }
    15. }