1. 防抖函数
<body><button id="myButton">点老子</button>
</body></html><script>function ois(fun, time) {let timeoutId;return (...a) => {clearTimeout(timeoutId)timeoutId = setTimeout(() => {fun(...a)}, time)}}function testFun() {console.log('防抖');}const debouncedFunction = ois(testFun, 1000);document.getElementById('myButton').addEventListener('click', () => {debouncedFunction()})
</script>
2. 节流函数的应用
function throttle(func, delay) {let lastExecTime = 0;return function (...args) {const currentTime = Date.now();if (currentTime - lastExecTime >= delay) {func.apply(this, args);lastExecTime = currentTime;}};
}// 示例用法:
function logThrottled() {console.log("节流函数触发了!");
}const throttledFunction = throttle(logThrottled, 1000);// 当需要节流的事件触发时,调用 throttledFunction
// 例如,滚动事件触发节流效果:
window.addEventListener("scroll", throttledFunction);
时小记,终有成。