小编典典

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

javascript

例如我想在10.00.00.00 am调用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>

我希望从此代码在00.30开始打开google,然后每隔1分钟就会再次打开它?该代码有什么问题?


阅读 366

收藏
2020-04-25

共1个答案

小编典典

您将需要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);
2020-04-25