javascript 如何每小时调用一个函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19847412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:01:37  来源:igfitidea点击:

How to call a function every hour?

javascript

提问by user2961971

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 I'm 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();
 }

回答by Igor

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. An alternative approach may be to poll the time every x many seconds/minutes, and fire it .getMinutes() == 0instead (similar to the first part of the if-statement), which may sacrifice (marginal) performance for (marginal) accuracy. Depending on your exact needs, I would play around with both solutions.

现在,此实现检查一次时间,设置延迟(或立即调用该函数),然后依靠 setInterval 进行跟踪。另一种方法可能是每 x 秒/分钟轮询一次时间,并.getMinutes() == 0改为触发它(类似于 if 语句的第一部分),这可能会为了(边际)准确性而牺牲(边际)性能。根据您的确切需求,我会尝试两种解决方案。

回答by HaukurHaf

Here is what should work (JSFiddle):

这是应该起作用的(JSFiddle):

function tick() {
  //get the mins of the current time
  var mins = new Date().getMinutes();
  if (mins == "00") {
    alert('Do stuff');
  }
  console.log('Tick ' + mins);
}

setInterval(tick, 1000);

回答by ZER0

What you probably want is something like that:

你可能想要的是这样的:

var now = new Date();
var delay = 60 * 60 * 1000; // 1 hour in msec
var start = delay - (now.getMinutes() * 60 + now.getSeconds()) * 1000 + now.getMilliseconds();

setTimeout(function doSomething() {
   // do the operation
   // ... your code here...

   // schedule the next tick
   setTimeout(doSomething, delay);
}, start);

So basically the first time the user get the access, you need to know what is the delay in millisecond to the next "hour". So, if the user access to the page at 8:54 (with 56 seconds and 123 milliseconds), you have to schedule the first execution after around 3 minutes: after the first one is done, you can call it every "hour" (60 * 60 * 1000).

所以基本上在用户第一次获得访问权限时,您需要知道到下一个“小时”的毫秒延迟是多少。所以,如果用户在 8 点 54 分(56 秒和 123 毫秒)访问页面,你必须在大约 3 分钟后安排第一次执行:在第一次执行完成后,你可以每隔“小时”调用一次( 60 * 60 * 1000)。

回答by Asenar

EDIT: Oops, I didn't see the " o' clock" things, so I edit my answer :

编辑:哎呀,我没有看到“o'clock”的东西,所以我编辑了我的答案:

var last_execution = new Date().getTime();
function doSomething(force){
  var current_time = new Date().getTime();
  if (force || (current_time.getMinutes() == 0)
  {
    last_execution = current_time;
    // something
    // ...
  }
  setTimeout(doSomething(false), 1000);
}
// force the first time
doSomething(true); 

回答by Steven Koch

// ... call your func now
let intervalId;
let timeoutId = setTimeout(() => {
  // ... call your func on end of current hour
  intervalId = setInterval(() => {
     // ... call your func on end of each next hours
  }, 3600000);
}, ((60 ? moment().minutes()) × 60 × 1000) - (moment().second() * 1000));