有些動作不該被連續觸發,例如連點送出按鈕、拖曳中的運算、滾動時的 heavy 計算。與其到處在業務程式碼裡加旗標,不如做一個通用的節流(throttle)包裝器。
function throttle(fn, ms) {
var last = (new Date()).getTime();
return (function () {
var now = (new Date()).getTime();
if (now - last > ms) {
last = now;
fn.apply(this, arguments);
}
});
}
值得注意的是 fn.apply(this, arguments) 這一行:this 被設為呼叫者本身,arguments 則原封不動轉傳。因此包裝後的函式對外看起來與原函式無異,這正是高階函式該有的樣子。
document.getElementById('pop').onclick = throttle(function () {
alert(this.id);
}, 2000);
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#pop { width: 100px; height: 100px; background: #ccc; }
</style>
</head>
<body>
<div id="pop">連續點我,每兩秒才會跳一次</div>
<script>
function throttle(fn, ms) {
var last = (new Date()).getTime();
return (function () {
var now = (new Date()).getTime();
if (now - last > ms) {
last = now;
fn.apply(this, arguments);
}
});
}
document.getElementById('pop').onclick = throttle(function () {
alert(this.id);
}, 2000);
</script>
</body>
</html>
這裡實作的是節流(throttle):固定時間窗內最多執行一次。另一個常見需求是防抖(debounce):事件停止觸發後才執行,例如搜尋框的即時查詢。兩者的差別在於「持續觸發時誰會被執行」——節流是週期性執行,防抖則是永遠等到最後一次。
function debounce(fn, ms) {
var timer;
return function () {
var args = arguments, self = this;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(self, args);
}, ms);
};
}
選哪一個取決於需求語意:要「即時回饋但別太頻繁」用節流,要「等使用者停下來再動作」用防抖。