June 11, 2012

How to prevent excessive function calls in JQuery

Question by tsvallender

I have an element which autosaves its contents via an AJAX call. Currently, whenever the contents change the autosave function is called. However, I’d like to limit this a bit to reduce the number of server requests. What would be the best way of editing the following code so save() is called no more than once every n seconds?

$("#editorInstance").contentChange(function() {
    save();
});

Answer by blockhead

If you don’t mind another library, underscore has a throttle method which can handle this:

throttle _.throttle(function, wait)

Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.

var throttled = _.throttle(updatePosition, 100);
$(window).scroll(throttled);

Answer by Starx

You can delay the execution of the function, using setTimeOut()

var init;
$("#editorInstance").contentChange(function() {
    init = setTimeOut(save, 60000); //After a minutes
});

//Do you forget to clear the timeout too
function save() {
     clearTimeOut(init);
     //Remaining function
}

Or, you might want to disable the editor, when it is being saved.

$("#editorInstance").contentChange(function() {
    $(this).attr('disabled', true);
    save();
    $(this).removeAttr('disabled');
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!