Friday, April 19, 2013

Custom setInterval() function javascript or jquery

Hello friends,

At some point of my jquery problem, i wanted to call a particular funtion 'n' times and in 'x' interval(in seconds). I relied on javascript's setInterval() method, but the catch is that it is called forever.

So I've made a jquery function which does the functionality as requiered by user.

var main = {};
// the funtion definition ...
main.TimerFunction = function (opts) {
// interval in seconds ...
var intervalTime = opts.IntervalInSeconds * 1000;
// cutomized setInterval method ...
var intervalId = setInterval(function () {
   // if the functionToExecute is to be called forever ...
   if ((opts.CallForever != undefined) && (opts.CallForever == true)) {
        opts.FunctionToExecute();
   }

   // if functionToExecute is to be called "n" times ...
   else if ((opts.TimesToCall != undefined) && (opts.TimesToCall != 0)) {
       for (var i = 0; i < opts.TimesToCall; i++) {
                opts.TimesToCall = opts.TimesToCall - 1;
                opts.FunctionToExecute();
                clearInterval(intervalId);
                main.TimerFunction(opts);

                break;
       }
   }                    

   // else clear intervalId ...
   else {
       clearInterval(intervalId);
   }
}, intervalTime);
};




Now if i want to execute a funtion just 3 times at the interval of 5 seconds, i'll  call the above function as :
var params = {};
params.FunctionToExecute = function () {
      alert('Hello World !');
};
params.CallForever =
false;     // true, if you want to call it forever ...
params.TimesToCall = 3;         // calling the FunctionToExecute 3 times ...
params.IntervalInSeconds = 5;   // FunctionToExecute will be called every 5 seconds ...
main.TimerFunction(params);     // pass the parameters, and call the function ...



Enjoy,

No comments: