tsvallender
tsvallender

Reputation: 2974

How to prevent excessive function calls in JQuery

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();
});

Upvotes: 0

Views: 281

Answers (3)

sissonb
sissonb

Reputation: 3780

This is how I would solve it,

$("#editorInstance").contentChange(function() {
    if(!window.saveTimeout)
        window.saveTimeout = setTimeOut(save(), 60000);
    else
        clearTimeout(window.saveTimeout);
        window.saveTimeout = setTimeOut(save(), 60000);
});

Upvotes: 1

blockhead
blockhead

Reputation: 9705

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);

Upvotes: 3

Starx
Starx

Reputation: 78971

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');
});

Upvotes: 2

Related Questions