Damian W
Damian W

Reputation: 568

JavaScript loop to call a different function every 30 seconds

I'm (poorly) attempting to create a simple page which loops between a clock + date, current weather, 7-day weather forecast, news and calendar events. Each of these 'items' are called upon using functions.

For example; I've created functions like:

displayTime();      // Time + date using Moment.js
currentWeather();   // Current weather using Forecast.io        (AJAX call)
forecastWeather();  // Weekly forecast of the weather           (AJAX call)
latestNews();       // Latest headlines from RSS source/s       (AJAX call)
calendarEvents();   // Calendar events from iCloud calendars

They all work perfectly when I call them on their own; but on jQuery document ready I want to call the clock + date function, wait 30 seconds, and then call the next function (which would be current weather). After all functions have been through the loop, I'd like the loop to go back to the clock and start all over again.

How would I be able to do this?

Re-edit: After the suggestion from Chop, I'd like to use something along the lines of the following - while the clock updates every second as planned, the functions don't switch over every 30 seconds.

jQuery(document).ready(function ($) {      
    function displayOne(){
        displayTime();
        setTimeout(displayTwo, 30000);
    }
    function displayTwo() {
        currentWeather();
        setTimeout(displayOne, 30000);
    }
    displayOne();
    setInterval(displayTime, 1000);
});

Upvotes: 2

Views: 2580

Answers (2)

Chop
Chop

Reputation: 534

You can chain them like this

function callFx(fx) {
    setTimeout(fx, 30000)
}

function function1() { // update weather
    callFx(function2)
}
function function2() { // update time
    callFx(function3)
}
function function3() { // some operation
    callFx(function1)
}

Or using setInterval

var functions = [function1, function2, function3]
var index = 0

setInterval(function() {
    functions[index]()
    if(!functions[++index]) index = 0
}, 30000)

The full code would be

jQuery(document).ready(function ($) {      
    function displayOne(){
        setTimeout(displayTwo, 30000)
    }
    function displayTwo() {
        currentWeather()
        setTimeout(displayOne, 30000)
    }
    displayOne()
    setInterval(updateTime, 1000)
})

Upvotes: 5

dnlbschff
dnlbschff

Reputation: 51

You could use the setInterval() to trigger calling another function that takes care of changing your widget content by calling the right one of your functions depending on the current state of your widget.

Upvotes: 1

Related Questions