Reputation: 314
I try to debounce a function using Underscore.js 1.6.0 but the function isn't called after the timeout set. I expect exactly one "o" in the output div, but there is none. Changing _.debounce(echo, 200)
to _.debounce(echo(), 200)
produces 10 o's which is not what I want. Same result on Chrome and Firefox on Mac OS X.
What am I doing wrong? Am I using _.debounce in the wrong way?
See http://jsfiddle.net/YmSGL/ for a working example.
function echo() {
var out = document.getElementById("out");
out.innerHTML = out.innerHTML + "o";
}
for (var i = 0; i < 10; i++) {
var wait = Math.floor(Math.random() * 100);
setTimeout(function() {
console.log("Calling echo @" + _.now());
_.debounce(echo, 200);
}, wait);
}
Upvotes: 2
Views: 1549
Reputation: 314
Thank you Felix Kling! The following code works:
function echo() {
var out = document.getElementById("out");
out.innerHTML = out.innerHTML + "o";
}
var echo2 = _.debounce(echo, 200);
for (var i = 0; i < 10; i++) {
var wait = Math.floor(Math.random() * 100);
setTimeout(function() {
console.log("Calling echo @" + _.now());
echo2();
}, wait);
}
If you would excuse me now, I have to bang my head to the wall.
Upvotes: 2