JavaScript
Article
By Sam Deering

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:

--ADVERTISEMENT--

//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
Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account