嗨我想在8到10点之间执行此功能。所以从8开始,它自动停在10。我在下面有这个代码,但它似乎有效,如果通过8点钟就不会执行。
var timeOut1 = setTimeout(function () {
var date = new Date();
if ((date.getHours() >= 20 && date.getMinutes() >= 00) || (date.getHours() <= 22 && date.getMinutes() <= 00)) {
$('#myModal').modal('show');
}
}, 1000);
document.write(timeOut1);
我试过setInterval也可以帮助我吗?
答案 0 :(得分:1)
您需要在此处使用setInterval()方法:
var timeOut1 = setInterval(function () {
由于setTimeout将在1000ms之后运行,即1秒,因此它不会再次检查你的时间,但是使用setInterval将每1秒运行一次并检查时间并执行代码。
var timeOut1 = setInterval(function () {
var date = new Date();
if ((date.getHours() >= 20 && date.getMinutes() >= 00) || (date.getHours() <= 22 && date.getMinutes() <= 00)) {
$('#myModal').modal('show');
}
}, 1000);
document.write(timeOut1);
评论回复:
如果需要,您可以清除间隔计时器,例如。关闭模态后,您不需要使用setInterval函数,因此在关闭模态时请使用以下代码:
clearInterval(timeOut1);
答案 1 :(得分:1)
这将帮助您在上午10点致电功能
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);
答案 2 :(得分:0)
现在写入,你的函数将在定义timeOut1后1000毫秒执行,并且只执行一次,如果if-condition的计算结果为false,则不会发生任何事情。如果您希望该函数重复检查您必须使用setInterval的时间。要在条件评估为真时间隔停止重复,您还必须清除间隔。
var intervalHandle = setInterval(function () {
var date = new Date();
if ((date.getHours() >= 20 && date.getMinutes() >= 00) || (date.getHours() <= 22 && date.getMinutes() <= 00)) {
$('#myModal').modal('show');
clearInterval(intervalHandle);
}
}, 1000);
答案 3 :(得分:0)
您应该在此处使用&&
而不是||
才能使其正常工作。每当时间为8且小于10时都会显示模态。希望我不迟到:)
var timeOut1 = setInterval(function () {
var date = new Date();
if ((date.getHours() >= 20 && date.getMinutes() >= 00) && (date.getHours() <= 22 && date.getMinutes() <= 00)) {
$('#myModal').modal('show');
}
}, 1000); document.write(timeOut1);