JavaScript 循环,每 30 秒调用一次不同的函数


JavaScript loop to call a different function every 30 seconds

我(糟糕地)试图创建一个简单的页面,该页面在时钟+日期,当前天气,7天天气预报,新闻和日历事件之间循环。这些"项"中的每一个都是使用函数调用的。

例如;我创建了如下函数:

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

当我自己调用它们时,它们都可以完美地工作;但是在jQuery文档准备就绪时,我想调用时钟+日期函数,等待30秒,然后调用下一个函数(这将是当前的天气)。在所有函数都完成循环后,我希望循环回到时钟并重新开始。

我该怎么做?

重新编辑:在 Chop 的建议之后,我想使用类似于以下内容的内容 - 虽然时钟按计划每秒更新一次,但函数不会每 30 秒切换一次。

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

你可以像这样链接它们

function callFx(fx) {
    setTimeout(fx, 30000)
}
function function1() { // update weather
    callFx(function2)
}
function function2() { // update time
    callFx(function3)
}
function function3() { // some operation
    callFx(function1)
}

或使用 setInterval

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

完整的代码将是

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

您可以使用 setInterval() 触发调用另一个函数,该函数通过根据小部件的当前状态调用正确的函数来更改小部件内容。