Custom JavaScript handler to process the last event occurring instead of every event

by Michael Henstock 7. April 2013 10:02

I recently had a requirement to bind to a browser resize event that would adjust an elements size. Now that's all well and fine except you can get hundreds of resize events firing during the user resizing the browser. What we really want is to apply the changes after the user has finished resizing the window.

Now, there are plenty of third party libraries that provide this capability and a lot more (the Reactive Extensions library by Microsoft is the first that comes to my mind []), but my requirements were very simple and didn't need a full library. All our requirements are for an event to be called back half a second after the resize events have stopped calling.

var __customEventsHandler;
(function (events) {
    var timers = { };
    events.waitForFinalEvent = function(callback, ms, uniqueId) {
        if(!uniqueId) {
            throw "must specify uniqueId";
        if(timers[uniqueId]) {
        timers[uniqueId] = setTimeout(callback, ms);
})(__customEventsHandler || (__customEventsHandler = {}));

This gives us a __customEventsHandler.waitForFinalEvent function that takes the callback to run when the events stop occurring, the expected timeout milliseconds to wait and an uniqueId that we specify for the bind event to allow the handler to contain whatever timeout identifiers it needs to cancel/complete the timeouts.

How we can call this is via the following code:

$(window).resize(function () {
    __customEventsHandler.waitForFinalEvent(function () {
        alert('resize complete!')
    }, 500, "my_window_resize");

With the alert appearing 500 milliseconds after no more resize events have occurred.