I could not get the underscore debounce method to work from within a requirejs module. As an alternative, I can make a pseudo-debounce method via the window.setTimeout, but then I have to test the timer manually.
Has anyone created a better alternative than this? Here is a jsfiddle of the problem: http://jsfiddle.net/ledlogic/gkY5C/
require.config({
paths: {
'jquery': 'http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.min',
'underscore': 'https://raw.github.com/documentcloud/underscore/master/underscore'
}
});
require(['jquery', 'underscore'], function ($, _) {
var flyStat = {
pct: -1,
delay: 0,
timeout: null,
rnd: function (i) {
flyStat.pct = Math.random() * 100.0;
flyStat.trns(i);
},
// report transient state. CALLED
trns: function (i) {
console.log("TRNS[" + i + "]: " + flyStat.pct);
},
// report final state, called immediately at end. CALLED
rpt: function () {
console.log("RPT: " + flyStat.pct);
},
// report final state, intended to be called from debounce. NOT CALLED
rptd: function () {
console.log("RPTD: " + flyStat.pct);
},
// report final state, setup timeout calls. CALLED
rpto: function(delay) {
if (flyStat.timeout) {
window.clearTimeout(flyStat.timeout);
}
flyStat.last = (new Date()).getTime();
flyStat.delay = delay;
flyStat.timeout = window.setTimeout(flyStat.rpto2, delay);
},
// report final state, called from timeout call. CALLED
rpto2: function() {
if (flyStat.last > flyStat.delay) {
console.log("RPTO2: " + flyStat.pct);
}
}
};
// Can debounce call back into a requires define block?
// NO.
function dbc() {
console.log("DBC: 1");
}
_.debounce(dbc, 10);
// Run a semi-lengthy running process (because of the console log activity, it lags a bit).
for (var i = 0; i < 1000; i++) {
flyStat.rnd(i);
// We want a debounced report, after 1 sec past the last one
// Do we get it?
// NO.
_.debounce(flyStat.rptd, 1000);
// Can we resort to classic timeout?
// YES.
flyStat.rpto(1000);
// Is there a better way?
// UNKNOWN.
}
// Immediate call at end (assumes we have sequential process with fixed known length and endpoint).
// Does this work?
// YES.
flyStat.rpt();
});