Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

javascript - 每小时调用一个函数(Call a function every hour)

I am trying to update information from a weather service on my page.(我正在尝试更新页面上的气象服务信息。)

The info should be updated every hour on the hour.(该信息应每小时更新一次。) How exactly do I go about calling a function on the hour every hour?(我该如何每小时每小时精确地调用一个函数?) I kind of had an idea but im not sure of how to actually refine it so it works... What I had in mind was something like creating an if statement, such as: (pseudo code)(我有点主意,但是我不确定如何真正地对其进行改进……我想到的就是创建一个if语句,例如:(伪代码)) //get the mins of the current time var mins = datetime.mins(); if(mins == "00"){ function(); }   ask by user2961971 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You want to check out setInterval : https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval(您想检出setIntervalhttps : //developer.mozilla.org/en-US/docs/Web/API/Window.setInterval)

It's a little hard to tell what you're trying to call with your code, but it would be something in the form of:(很难说出您要用代码调用什么,但这将是以下形式:) function callEveryHour() { setInterval(yourFunction, 1000 * 60 * 60); } If you want it every hour, try something like:(如果您希望每小时进行一次,请尝试以下操作:) var nextDate = new Date(); if (nextDate.getMinutes() === 0) { // You can check for seconds here too callEveryHour() } else { nextDate.setHours(nextDate.getHours() + 1); nextDate.setMinutes(0); nextDate.setSeconds(0);// I wouldn't do milliseconds too ;) var difference = nextDate - new Date(); setTimeout(callEveryHour, difference); } Now, this implementation checks the time once, sets the delay (or calls the function immediately), and then relies on setInterval to keep track after that.(现在,此实现检查一次时间,设置延迟(或立即调用函数),然后依靠setInterval跟踪此时间。) An alternative approach may be to poll the time every x many seconds/minutes, and fire it .getMinutes() == 0 instead (similar to the first part of the if-statement), which may sacrifice (marginal) performance for (marginal) accuracy.(另一种方法是每隔x秒钟/分钟轮询一次时间,然后将其.getMinutes() == 0 (类似于if语句的第一部分),这可能会牺牲(边际)性能(边际) ) 准确性。) Depending on your exact needs, I would play around with both solutions.(根据您的确切需求,我会同时考虑两种解决方案。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...