Consider this:
setTimeout(function(){...}, 1000);
It runs the function after 1 second. I was confused if I want to a function runs at 08:30:00 but my script starts just now (Date.now()
), how should I estimate the milliseconds until then?
Consider this:
setTimeout(function(){...}, 1000);
It runs the function after 1 second. I was confused if I want to a function runs at 08:30:00 but my script starts just now (Date.now()
), how should I estimate the milliseconds until then?
You'll need to create a date that is the same day as the day that the page is being accessed and set the time portion of that date to 8:30. Then you can simply subtract the current time from that time to get the difference in milliseconds. Once you know the difference, you can set your timer for that delay.
let now = new Date();
console.log("Current time is: " + now.toLocaleTimeString());
let targetTime = new Date();
targetTime.setHours(20); // 8 pm
targetTime.setMinutes(30); // 30 minutes
targetTime.setSeconds(0); // 0 seconds
console.log("Target time is: " + targetTime.toLocaleTimeString()); // 8:30 PM
let delay = targetTime - now; // Get difference in milliseconds
console.log(delay + " milliseconds (" + delay/1000 + " seconds, " + (delay/1000/60).toFixed(2) + " minutes" + ") until 8:30");
setTimeout(function(){
console.log("time's up!");
}, delay);