Handy JavaScript tip of the day: functions can be used as array indexes
When I hook into text fields, I add a “bounce” delay to avoid processing overhead. When a key is pressed, I start a timer set for 1-2 seconds, which calls my processing method. If the timer is running, it’s reset. The upshot is that processing does not occur until 1-2s after the user stops typing. Example:
var timer;
function bounce(callback, time)
{
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(callback, time);
}
$('#myElement').keypress(function() { bounce(processFunction, 2000); });
This breaks when you want that behavior with multiple elements on the same page, since the timer only fires one callback; if you type into the second field before the first callback fires, it never fires. But since you can use functions as array indexes, you can do:
var timers = [];
function bounce(callback, time)
{
if (timers[callback]) {
clearTimeout(timers[callback]);
}
timers[callback] = setTimeout(callback, time);
}
$('#myElement').keypress(function() { bounce(processFunction, 2000); });
$('#myOtherElement').keypress(function() { bounce(processFunction, 2000); });

February 23rd, 2008 at 6:13 pm
The exact solution I was looking for to this exact same problem!
Cheers!