Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a javascript function at a specific time of day

Tags:

javascript

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?

like image 413
ramazan murat Avatar asked Dec 15 '10 21:12

ramazan murat


People also ask

How do you call a function with a delay?

Answer: To delay a function call, use setTimeout() function. function-name − The function name for the function to be executed.

Can I call a function multiple times JavaScript?

In order to run a function multiple times after a fixed amount of time, we are using few functions. setInterval() Method: This method calls a function at specified intervals(in ms). This method will call continuously the function until clearInterval() is run, or the window is closed.

How can we call a function automatically after waiting for some time in jQuery?

Answer: Use the jQuery delay() method You can use the jQuery delay() method to call a function after waiting for some time. Simply pass an integer value to this function to set the time interval for the delay in milliseconds.


1 Answers

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); 
like image 114
Chris Morgan Avatar answered Sep 18 '22 12:09

Chris Morgan