【问题标题】:JQuery run every 5 minutes past the hour 5,10,15...55JQuery 每隔 5 分钟运行一次 5,10,15...55
【发布时间】:2019-10-11 11:46:07
【问题描述】:

我希望每小时每 5 分钟运行一次函数,即 08:05、08:10、08:15 等......全天

我该如何适应:

 setTimeout(function(){ 
    xxxxxxx() 
 }, 300000);

检测当前时间 - 如果是 5 的倍数则运行 xxxxxx() 函数?

【问题讨论】:

  • 如果您使用 jquery(已标记,但不应该使用),那么您希望浏览器全天打开吗?您不希望它在服务器端运行,类似于计划任务吗?

标签: javascript jquery time settimeout


【解决方案1】:

使用setInterval 每秒调用一次函数。 然后使用当前时间过滤器,一分钟可被 5 整除,秒数为零。

var timer = 0;
timer = setInterval(function(){ 
	var currentdate = new Date();  
	if(currentdate.getMinutes() % 5 == 0 && currentdate.getSeconds() == 0) {
		console.log("Alarm");
	}
}, 1000);
//to stop: clearInterval(timer);

【讨论】:

    【解决方案2】:

    这很简单:

    • 使用setTimeout() 等到您到达 5 分钟边界
    • 使用setInterval()每5分钟调用一次函数

    function dosomething() {
      console.log("dosomething() called at " + new Date().toISOString());
    }
    
    var FIVEMINUTES = 5 * 60 * 1000;
    var timeSincePrev = new Date() % FIVEMINUTES;
    var timeUntilNext = timeSincePrev === 0 ? 0 : (FIVEMINUTES - timeSincePrev);
    
    setTimeout(function() {
      dosomething(); // execute now
      setInterval(dosomething, FIVEMINUTES); // and after every 5 minutes
    }, timeUntilNext);

    【讨论】:

      猜你喜欢
      • 2013-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多