98

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?

ramazan murat
  • 1,227
  • 1
  • 10
  • 8

5 Answers5

165

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);
Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
  • working thanks.. one more thing i want call that function every 5 mins later from 10 am how can do it? – ramazan murat Dec 15 '10 at 22:06
  • 8
    You can use [`setInterval`](https://developer.mozilla.org/en/DOM/window.setInterval). `interval = setInterval(func, 5*60*1000);` then you can `clearInterval(interval)` when you don't want to keep going. – Chris Morgan Dec 15 '10 at 22:13
  • interval is valid from 10 am or valid when i open the page?? – ramazan murat Dec 15 '10 at 22:22
  • setTimeout(openAPage, millisTill10); // this is ok 10.00 am my funk called.. but after when i write setInterval(openAPage, 5*1000); not after 10.00 am instead of after page displayed interval begin to work.. – ramazan murat Dec 15 '10 at 22:25
  • 1
    change it to setTimeout(function{openAPage(), setInterval(openAPage, 5*1000)}, millisTill10). Then the initial timer (which goes off at 10) will perform the initial call to openAPage and also set up the interval. – KeithS Dec 15 '10 at 22:29
  • doesnt working.. i will post the whole script whats wrong with that look at tho code my send up pls – ramazan murat Dec 15 '10 at 22:35
  • Use `;`, not `,`, to separate the `openAPage()` and `setInterval`. – Chris Morgan Dec 15 '10 at 22:54
  • I have written an example script that prints a message every 3 seconds: http://jsfiddle.net/jarble/qnVy6/1/ – Anderson Green Jan 25 '13 at 04:57
  • If no one accessed the website at 10am, will it trigger if someone visits at 11am? – Lucas Bustamante May 11 '17 at 18:53
  • @LucasBustamante: as described, the timeout triggers at the next 10am. – Chris Morgan May 19 '17 at 03:01
  • How reliable is this? What happens if the user puts the computer to sleep and then switches it on again? Or if google chrome sleeps the tab? Is setTimeout smart enough when I reopen the window to determine that time has passed? – simondefreeze Apr 15 '20 at 22:52
  • @simondefreeze When the tab is in the background, it should still be reliable. But for the computer sleeping, it’s definitely unreliable, and no reliable client-driven approach exists—repeated shorter timers is the best you can do. One possible alternative can be to push something from the server at the right time, if the computer is awake and online. See pushManager in a service worker for that. But calendar-based awakening would require a calendarManager, which has never gone anywhere (e.g. https://github.com/w3c/ServiceWorker/issues/838). – Chris Morgan Apr 19 '20 at 13:57
  • Thanks @ChrisMorgan I have gone for the repeated short timer approach, but that is an interesting idea to push something from the server – simondefreeze Apr 20 '20 at 01:31
  • Really cool :) But you should not rely on this since it's not so accurate and the main problem is when computer goes to sleep it's put on hold and resumes when woke up. So it's better to set to some repeating watching period and check for >= of the specific time e.g. each second. – VirtualVAT Jun 14 '23 at 19:34
23

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);
Harijs Krūtainis
  • 1,261
  • 14
  • 13
1

The best algorithm here is great but there could be a problem if computer slept some time during this period especially if there is a long time to "time". In this case waiting time period will be longer for sleeping time since "timeout" is put on hold while sleeping. Also setTimeout() is not so accurate to rely on it for so long period. If there is a need to watch for some long period I'd suggest modified algorithm above to check for the specified time each e.g. 1 second:

const start = new Date();
var millisTill10 = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 10, 0, 0, 0) - start;
if (millisTill10 < 0)
 millisTill10 += 86_400_000; // it's after 10am, try 10am tomorrow.
function timeWatcher() {
 if (new Date() - start >= millisTill10)
  alert("It's 10am!");
 else
  setTimeout(timeWatcher, 1000);
}
timeWatcher();
VirtualVAT
  • 61
  • 1
  • 5
0

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.

KeithS
  • 70,210
  • 21
  • 112
  • 164
0

Try this

$(document).ready(function() {
  setTimeToTrigger();
});

function setTimeToTrigger(){
  var dt = new Date();
  var hour = dt.getHours();
  var minute = dt.getMinutes() ;
  var seconds = dt.getSeconds();

  if(hour<10){
    nexthour=9;
  }else if(hour<22){
    nexthour=21;
  }else{
    nexthour=23-hour+9;
  }
  delaytime=(nexthour-hour)*60*60+(59-minute)*60+(59-seconds);
  alert('will be triggered in :'+ delaytime + ' seconds');
  setTimeout( function() {
    alert("The time is 10:00");
  }, delaytime*1000); 
}
<html>
<head>
  <title>alert at specific time</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
  <h3>Alert at at 10:00 AM and 10:PM</h3>
</body>
</html>
Merrin K
  • 1,602
  • 1
  • 16
  • 27