<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button id="throttle">节流</button> <button id="debounce">防抖</button> <script> function throttle(callback, delay) { let start = 0 return function (...args) { const current = Date.now() if (current - start > delay) { start = current callback.apply(this, args) } } } function debounce(callback, delay) { return function (...args) { if (callback.timeoutId) { clearTimeout(callback.timeoutId) } callback.timeoutId = setTimeout(() => { delete callback.timeoutId callback.apply(this, args) }, delay) } } function handlerClick() { console.log('---') } document.getElementById('throttle').onclick = throttle(handlerClick, 2000) document.getElementById('debounce').onclick = debounce(handlerClick, 2000) </script> </body> </html>
来源:https://www.cnblogs.com/stefzi/p/12294686.html