JavaScript
Article

jQuery creating mutiple setInterval functions

By Sam Deering

Using jQuery to create mutiple timeouts for mutiple time based events. I ran into a quick solution to a problem when declaring more than one setInterval function to automate refresh time intervals on a widget. Hopefully a quick few seconds read will help some of you save more time debugging.

This example uses widgets to auto refresh based on specific timers.

var wid = v['widgetId'];
//set refresh for x seconds
setInterval(function() {
    console.log('refreshing widget '+wid);
    refreshWidgetContent(wid);
}, intV);

//output:
refreshing widget 6
refreshing widget 6
refreshing widget 6

To get it to work we need to declare the variable inside the setInterval function like this:

//set refresh for x seconds
setInterval(function() {
    var wid = v['widgetId'];
    console.log('refreshing widget '+wid);
    refreshWidgetContent(wid);
}, intV);

//output:
refreshing widget 1
refreshing widget 3
refreshing widget 6

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

No Reader comments

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.