oOo--STAR--oOo
oOo--STAR--oOo

Reputation: 438

How to limit a call to function?

I'm currently looking for the best solution to limit the number of requests to a function.

Example:

function CheckData() {
    if (d == "newdata") {
        GetData(2);
    }
}

function GetData(getcheck) {
    // Ajax Request here
}

The solution I am looking for is a way so that when CheckData calls GetData is there a way to limit how often it can call GetData, or better still if there is a bulk of requests that has suddenly come through, is there a way to make it say only get the last request? So basically can it check the frequency of requests so that you can say its stopped a bulk of requests send the last one now?

I am just looking for a way to limit how often CheckData can call GetData but the best possible way to minimize wait.

I have looked at a few solutions and I am not sure how to apply it to this situation.

Upvotes: 3

Views: 3507

Answers (1)

Simon Boudrias
Simon Boudrias

Reputation: 44649

Option 1
Usuals pattern to limit the number of time a function can be called are:

throttle and debounce

(You can also see similar implementation in underscore.js)

Option 2
Although for ajax, you could create a queue system to limit one request at a time on the same ressources.

Option 3
Or, if your function always get the same ressources, just check if the request is over or not:

var GetData = (function() {
    var running = false;
    return function(getcheck) {
        // exit if ajax is running
        if ( running ) { return; }

        running = true;

        $.ajax(/* go */)
            .done(function() {
                /* do stuff with data */

                // call it over
                running = false;
            });
    }
}());

function CheckData() {
    if (d == "newdata") {
        GetData(2);
    }
}

Upvotes: 4

Related Questions