简体   繁体   English

如何每隔一小时更新一次变量,而无需用户刷新页面?

[英]How to update variable every full hour without refresh page by user?

Controller: 控制器:

$number = rand(1, 100);

View: 视图:

<div id="lucky">
   Your lucky number: <?php echo $number ?>.
</div>

How can I update the value for $number every hour without manually refreshing the page? 如何在不手动刷新页面的情况下每小时更新$number的值? I can use setInterval from JavaScript/jQuery , but I would like do it exactly at full hour (0:00, 1:00, 2:00 etc...). 我可以使用JavaScript / jQuery中的 setInterval ,但是我想完全在一个小时(0:00、1:00、2:00等)执行此操作。 What is the best way to do this? 做这个的最好方式是什么? I can use PHP, CRON, JS and JS frameworks... 我可以使用PHP,CRON,JS和JS框架...

Try finding out what time it is now, figure out how long it is until the next full hour, then wait that long: 尝试找出现在的时间,找出下一个完整小时需要多长时间,然后等待很长时间:

function doSomething() {
    var d = new Date(),
        h = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() + 1, 0, 0, 0),
        e = h - d;
    if (e > 100) { // some arbitrary time period
        window.setTimeout(doSomething, e);
    }
    // your code(May be an ajax call to show lucky num)
}

The check for e < 100 is just to make sure you don't do setTimeout on something like 5 ms and get it a crazy loop. e <100的检查只是为了确保您不对5毫秒之类的时间执行setTimeout并使其疯狂循环。

Here you go with a solution 在这里你有一个解决方案

 var d = new Date(); var firstTrigger = 60000* (60 - d.getMinutes()); // This is for 1st Time Trigger setTimeout(function(){ console.log("1st time trigger", rand(1, 100)); // This is continuous trigger every full hour setInterval(function(){ console.log("Continuous trigger every hour", rand(1, 100)); }, 3600000); }, firstTrigger); 

In your case, instead of console.log you will trigger your code. 在您的情况下,您将触发代码,而不是console.log

Hope this will help you. 希望这会帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM