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

No Reader comments

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

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