- 函數(shù)節(jié)流: 指定時(shí)間間隔內(nèi)只會(huì)執(zhí)行一次任務(wù)
- 函數(shù)防抖: 任務(wù)頻繁觸發(fā)的情況下越除,只有任務(wù)觸發(fā)的間隔超過(guò)指定間隔的時(shí)候简珠,任務(wù)才會(huì)執(zhí)行
例如:輸入框輸入文字如下:1111111111111111111111...
- 函數(shù)節(jié)流:當(dāng)用戶(hù)持續(xù)輸入1的過(guò)程中,從你開(kāi)始輸入1開(kāi)始計(jì)時(shí)惭墓,到第1s坛梁,執(zhí)行函數(shù)
- 函數(shù)防抖:當(dāng)用戶(hù)持續(xù)輸入1的過(guò)程中,并不會(huì)執(zhí)行函數(shù)腊凶,當(dāng)用戶(hù)停止輸入1s后划咐,執(zhí)行函數(shù)
以下是實(shí)現(xiàn)的代碼,我忘了引用誰(shuí)的了……
函數(shù)節(jié)流
<input>
<script>
let text = document.querySelector("input")
function throttle(fn, interval = 1000) {
let canRun = true;
return function () {
if (!canRun) return;
canRun = false;
setTimeout(() => {fn();canRun = true;}, interval);
};
}
text.oninput = throttle(()=>{console.log(text.value)})
</script>
函數(shù)防抖
<input>
<script>
let text = document.querySelector("input")
function debounce(fn, interval = 1000) {
let timeout = null;
return function () {
clearTimeout(timeout);
timeout = setTimeout(() => {fn()}, interval);
};
}
text.oninput = debounce(()=>{console.log(text.value)})
</script>