Sometimes we need to run multiple JavaScript timers in parallel, especially when we have to handle multiple repeated animations. In this post I will show you the implementation of a simple utility function to accomplish this task. This function makes use of the jQuery $.extend()
method for its default options. The code is as follows:
var createTimer = function(options) { options = $.extend({ element: 'body', counter: 0, limit: 10, interval: 1000 }, options); setInterval(function() { options.counter++; if(options.counter == options.limit) { options.counter = 0; } $(options.element).text(options.counter); }, options.interval); };
You can set the limit, counter and interval values to whatever value you need to make your timers work as you want. If you want to improve this basic function, you can also specify a callback
option to run a function every time the timer runs. A simple example:
$(function() { createTimer({ element: '#timer1', limit: 11 }); createTimer({ element: '#timer2', limit: 11 }); createTimer({ element: '#timer3', limit: 11 }); });
You can see the demo below.
just simple timers for basic purpose but I think a lot of people prefer awesome & cool timers