Call a javascript function at a specific time of day

Javascript

Javascript Problem Overview


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

<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?

Javascript Solutions


Solution 1 - Javascript

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

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);

Solution 2 - Javascript

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);

Solution 3 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionramazan muratView Question on Stackoverflow
Solution 1 - JavascriptChris MorganView Answer on Stackoverflow
Solution 2 - JavascriptHarijs KrūtainisView Answer on Stackoverflow
Solution 3 - JavascriptKeithSView Answer on Stackoverflow