文章

常用js

防抖 # js 复制 1 2 3 4 5 6 7 8 9 10 11 12 13 14 function debounce(fn, delay) { let timer; return function (...args) { timer && clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; } // 测试 function task(arg) { console.log("run task" + arg); } const debounceTask = debounce(task, 1000); window.addEventListener("scroll", () => debounceTask(11)); 节流 # js 复制 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 function throttle(fn, delay) { let last = 0; return function (...args) { const now = Date.now(); if (now - last < delay) return; last = now; fn.apply(this, args); }; } // 测试 function task() { console.log("run task"); } const throttleTask = throttle(task, 1000); window.addEventListener("scroll", throttleTask);

2024-06-16 · 1 分钟 · 130 字 · Linlccc