jQuery Timeout Function
written by: ryan coughlin
UPDATE: Edited the code thanks to Adrian Green. Thanks for the comment
jQuery does offer callbacks for most of its functions, but what if you want to delay or timeout a certain effect or function there isn’t a function made for that. This article should help you achieve that.
Old School JavaScript
I have been trying to search for a nice and reusable way to use jQuery to timeout effects or functions. We are familiar with using the traditional JavaScript function setTimeout():
setTimeout (function,timeout);
After putting in some data we can come up with something like this:
setTimeout (showBox(),2500);
Remember that the value 2500 is in MS (milliseconds), we equates to 2.5 seconds. When this function is called, it will execute 2500ms later. I was using this for one of my projects where I wanted two effects/functions not after, but during. I could have used very handy jQuery callback and load in a function, but it would have been executed after the first function is completed.
Let’s Start Delaying Effects – The Code
Lets jump right into the belly of the beast and view the code to call our handy jQuery timeout function. Essentially we have a small jQuery plugin. We define the function as: $.idle()
jQuery.fn.idle = function(time){
var i = $(this);
i.queue(function(){
setTimeout(function(){
i.dequeue();
}, time);
});
};
You see on the first line above we create the idle function: jQuery.fn.idle. We created the variable I to store $(this), which is going to be element that is running the $.idle(); function.
We then use the jQuery queue(); function whose documentation can be found on the jQuery website. Then we attach the $(this); variable we created called: i to it, and create the setTimeout(), which then uses dequeue(); with our variable connected to it.
The last part, where we create the time parameter for the function, so we call the following code and:
$.idle(2500);
time gets replaced with the user input of 2500ms to the function. Say if you want to call a function you can use it in this context instead of the messy old fashion setTimeout(); function.
$('.myelement').fadeIn().idle(2000).fadeOut('slow');
The above simple reads: fade in my element, then wait 2000ms, slowly fade out the same element. BOOM! There it is, the quick n’ dirty method to delaying functions using jQuery.
Take a peak at some more?
-
http://www.bestqualitypools.info mike villa
-
Adrian Green
-
http://james.revillini.com James Revillini
-
http://james.revillini.com James Revillini
-
http://felipetonello.com felipe tonello
-
http://www.stockvirtual.com Patrick
-
http://www.paragarora.com Parag Arora
-
http://www.hilalcelikhalat.com Serhan
-
http://Yourwebsite... Zach
-
http://Yourwebsite... salih0vicX
-
http://Yourwebsite... Onofrei George
-
http://Yourwebsite... timmers
-
Psivadasan