複数のイベントから開始できるアクションをデバウンスするにはどうすればよいですか? 動作を示すための例を次に示します: http://jsfiddle.net/eXart/2/
<input type="text" id="t">
<div id="x"></div>
<script>
function debounce(fn, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
function doStuff(){
document.getElementById("x").innerHTML +="<br>stuff";
}
var t = document.getElementById("t");
t.onchange = debounce(function(){ doStuff() }, 500);
t.onblur = debounce(function(){ doStuff() }, 500);
</script>
テキスト ボックスにテキストを入力してクリックすると、「stuff」が 1 回ではなく 2 回表示されることがわかります。これは、各イベントが独自のデバウンス インスタンスを取得しているためです。イベント間でデバウンス インスタンスをどのように共有しますか?