Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

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,

Thursday, March 21, 2013

What is jquery one function?

jQuery one() is a function which provides single-use event handling. By single-use I mean that the event will be executed/handled only once.
For Example:

$('YOUR_SELECTOR').one('click', function(){
     alert('1. This message will be displayed only once.');
});
http://api.jquery.com/one/

Interestingly the same functionality can be executed by jQuery on() function , as follows:

$('YOUR_SELECTOR').on("click", function(event) {
    alert('2. This message will be displayed only once.');
    $(this).off(event);
});
http://api.jquery.com/on/


Thank You,