Here's a modification of CMS's solution that can be called in multiple places in your code:
var waitForFinalEvent = (function () {
var timers = {};
return function (callback, ms, uniqueId) {
if (!uniqueId) {
uniqueId = "Don't call this twice without a uniqueId";
}
if (timers[uniqueId]) {
clearTimeout (timers[uniqueId]);
}
timers[uniqueId] = setTimeout(callback, ms);
};
})();
Usage:
$(window).resize(function () {
waitForFinalEvent(function(){
alert('Resize...');
//...
}, 500, "some unique string");
});
CMS's solution is fine if you only call it once, but if you call it multiple times, e.g. if different parts of your code set up separate callbacks to window resizing, then it will fail b/c they share the timer
variable.
With this modification, you supply a unique id for each callback, and those unique IDs are used to keep all the timeout events separate.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…