在一天中的特定时间调用 javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4455282/
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-08-23 12:28:07  来源:igfitidea点击:

Call a javascript function at a specific time of day

javascript

提问by ramazan murat

for example i want to call a js function at 10.00.00.00 am how can i do?

例如,我想在上午 10.00.00.00 调用一个 js 函数,我该怎么办?

<script type="text/javascript">

var now = new Date();

var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 30, 0, 0) - now;

setTimeout(function{openAPage(), setInterval(openAPage, 60*1000)}, millisTill10)

function openAPage() {

var startTime = new Date().getTime();
var myWin = window.open("http://google.com","_blank")
var endTime = new Date().getTime();
var timeTaken = endTime-startTime;


document.write("<br>button pressed@</br>")
document.write(new Date(startTime));
document.write("<br>page loaded@</br>")
document.write(new Date(endTime));
document.write("<br>time taken</br>")
document.write(timeTaken);

myWin.close()

}

</script>

i expect from this code at 00.30 it will open google and then every 1 minute later it will do it again? whats wrong with that code?

我希望从这个代码在 00.30 开始它会打开谷歌,然后每 1 分钟后它会再做一次?那个代码有什么问题?

回答by Chris Morgan

You'll need setTimeoutto set a timer and Dateto calculate how long the timer needs to go until it triggers.

您需要setTimeout来设置计时器和Date来计算计时器需要多长时间才能触发。

var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
if (millisTill10 < 0) {
     millisTill10 += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function(){alert("It's 10am!")}, millisTill10);

回答by Harijs Krūtainis

My solution for running a script at a specific time, btw no error checking for negative timeout.

我在特定时间运行脚本的解决方案,顺便说一句,没有错误检查负超时。

//year, month 0-11, date, hour, min (can add ,sec,msec)
var eta_ms = new Date(2015, 0, 21, 17, 0).getTime() - Date.now();
var timeout = setTimeout(function(){}, eta_ms);

回答by KeithS

Assuming the code is located on a web page that will be loaded before 10:00 and will still be viewed at 10:00, you can use setTimeout()to set up a timed event. the function takes some JS statement to execute, and the number of milliseconds before it should execute. You can find this second part pretty easily with the built-in date functions.

假设代码位于将在 10:00 之前加载并且仍会在 10:00 被查看的网页上,您可以使用setTimeout()来设置定时事件。该函数需要一些 JS 语句来执行,以及它应该执行之前的毫秒数。您可以使用内置的日期函数轻松找到第二部分。