Gaurav Kumar Gaur
Gaurav Kumar Gaur

Reputation: 13

Run JavaScript function at fixed time on daily

I have a HTML Page that's run a java script function and fill random data in html table. I want to run that function @ 9 AM on daily basis automatically. So how is it possible?

my HTML page is --

<!DOCTYPE html>
<html>
<body onload="myFunction()";>

<p>Click the button to display a random number between 1 and 9.</p>

<table style="width:100%" id="t01" border="1">
<tr>
    <th>Time</th> 
    <th>A</th>
    <th>B</th>
    <th>C</th>
    <th>D</th>
    <th>E</th>
    <th>F</th>
  </tr>
  <tr>
    <td>09:00AM</td>
    <td><p id="demo"></p></td>
    <td><p id="demo1"></p></td>
    <td><p id="demo2"></p></td>
    <td><p id="demo3"></p></td>
    <td><p id="demo4"></p></td>
    <td><p id="demo5"></p></td>
</tr>
</table>
<script>
function myFunction() {
  var a = Math.floor((Math.random() * 9) + 1);
  var b = Math.floor((Math.random() * 9) + 1);
  var c = Math.floor((Math.random() * 9) + 1);
  var d = Math.floor((Math.random() * 9) + 1);
  var e = Math.floor((Math.random() * 9) + 1);
  var f = Math.floor((Math.random() * 9) + 1);
  document.getElementById("demo").innerHTML = a;
  document.getElementById("demo1").innerHTML = b;
  document.getElementById("demo2").innerHTML = c;
  document.getElementById("demo3").innerHTML = d;
  document.getElementById("demo4").innerHTML = e;
  document.getElementById("demo5").innerHTML = f;
}
</script>
</body>
</html>

Upvotes: 1

Views: 331

Answers (2)

figbar
figbar

Reputation: 794

var now = new Date();
var millisTill9 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 9, 0, 0, 0) - now;
if (millisTill9 < 0) {
     millisTill9 += 86400000; // it's after 9am, try 9am tomorrow.
}
setTimeout(function(){alert(myFunction())}, millisTill9);

see: Call a javascript function at a specific time of day

EDIT--------- This is a timer which compares the current time to when you want your script to execute.

Upvotes: 2

maximus1127
maximus1127

Reputation: 1036

I would do something like set a localStorage variable and iterate over it every second.

localstorage.setItem('timeToRunIt', '1000'); //10:00 am without the colon

setTimeout(function(){
var now = new Date;
 if((now.getHours() +""+ now.getMinutes())== localStorage.getItem(timeToRunIt)){
 //run code here
}
}, 1000)

of course, that's going to run 60 times in the 10:00 minute for am and pm because it's only checking if the hours and the minutes equals "1000" every second. you could set a pause line in there for a minute after it runs if you want.

Upvotes: 0

Related Questions