tags:

views:

66

answers:

4

I have a JavaScript function which actually ends up making a server-side call. I want to limit the rate at which this function can be called.

What is an easy way I can limit how fast my javascript function will get called by say 200-500 milliseconds or so? Should I use a javascript timer control?

+1  A: 

You can create a flag that is raised when the function is called and start a timer and if this flag is raised then you can not call the function, then after a certain time, the timer is called and he turns off the flag, allowing you to call the function again.

The flag can be anything, like a bool or something.

Ólafur Waage
A: 

try setinterval( "function()", 500)

Jose
This calls the function every 500ms, but from my understanding Hendo doesn't want to call the function every 500ms. Just the ability to do so.
hora
I misunderstood, my bad
Jose
A: 

This will not allow the function to run if less than 500 milliseconds have passed since the last call.

(function(window, undefined){
    var canCall = true;
    window.funcName = function(){
        if (!canCall) 
            return;
        //Your function
        canCall = false;
        setTimeout(function(){
            canCall = true;
        }, 500);
    }
})(window);
M28
A: 
fooCanBeCalled = true;
function foo(){
   if(!fooCanBeCalled) return;
   //Whatever you want to do
   fooCanBeCalled = false;
   setTimeout(function(){
      {
         fooCanBecalled = true;
      }
   , delayInMilliseconds);
}
ItzWarty
He posted it later and his code exposes a global variable and still gets +1? -____-
M28