Reputation: 15
Hi I would like to execute this function between 8 and 10 o'clock. So it starts at 8 and it stops at 10 automatically. I have this code below, but it doesen seem to work, it wont execute if passes 8 o'clock.
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);
I tried setInterval alsoCan someone help me with this?
Upvotes: 0
Views: 2296
Reputation: 1072
You should have &&
here instead of ||
to make it work. Whenever time is 8 AND less than 10 show modal. Hope im not late :)
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);
Upvotes: 0
Reputation: 85613
You need to use setInterval() method here:
var timeOut1 = setInterval(function () {
As setTimeout would function after 1000ms i.e. 1 second, so it is not going to check your time ever forth again, but using setInterval would run every 1 second and check for the time and the code is executed.
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);
Comment response:
When needed you can clear the interval timer, for eg. you need not to use the setInterval function after closing the modal, so use the following code when you close the modal:
clearInterval(timeOut1);
Upvotes: 1
Reputation: 96
As written now your function will be executed 1000 ms after timeOut1 has been defined, and it will execute only once, if the if-condition evaluates to false, nothing will happen. If you want the function to repeatedly check the time you have to use setInterval instead. To have the interval stop repeating once the condition evaluates to true you also have to clear the interval.
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);
Upvotes: 0
Reputation: 1100
this will help you to call function at 10am
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);
ref: Call a javascript function at a specific time of day
Upvotes: 1