[英]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. 我(很少)尝试创建一个简单的页面,该页面在时钟+日期,当前天气,7天天气预报,新闻和日历事件之间循环。 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). 但是在准备好jQuery文档时,我想调用clock + date函数,等待30秒,然后调用下一个函数(这将是当前天气)。 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. 重新编辑:根据Chop的建议,我想按以下方式使用某些内容-尽管时钟按计划每秒更新一次,但功能不会每30秒切换一次。
jQuery(document).ready(function ($) {
function displayOne(){
displayTime();
setTimeout(displayTwo, 30000);
}
function displayTwo() {
currentWeather();
setTimeout(displayOne, 30000);
}
displayOne();
setInterval(displayTime, 1000);
});
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 或使用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)
})
您可以使用setInterval()来触发调用另一个函数,该函数通过根据窗口小部件的当前状态调用正确的一个函数来更改窗口小部件的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.