jQuery does offer callbacks for most of its functions, but what if you want to delay/timeout a certain effect or function. Well with this article, this should help you achieve that.
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
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.
The solution for this? Quite simple, check out the jQuery $ function, which allows us to call jQuery as “$” the example is below.
(function($) {
// Within this function $ is a reference to jQuery
// I love this framework
})(jQuery);
Lets jump right into the belly of the beast and view the code to call our handy jQuery timeout function.
(function($){
jQuery.fn.idle = function(time){
var i = $(this);
i.queue(function(){
setTimeout(function(){
i.dequeue();
}, time);
});
};
})(jQuery);
This might look like a bit overload, but it is really simple, we just learned how to create the skeleton of the function, so without it we:
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 200ms or 2 seconds then slowly fade out the same element. BOOM! There it is, the quick n’ dirty method to timing functions out using jQuery.
