Triggering event at a given time

Combining the Date object and the setTimeout method, we can achieve an JavaScript equivalent to Unix cron, ie, trigger an event at a given time.
It must, however, that the page containing the code is displayed to make the events.

The principle is:

  1. To fix the date of the event, which will be in the demo the display of a message on the page.
  2. Then we find the current date with the Date object and calculate the difference with the time of the event.
  3. Then we launch setTimeout with this difference.

Code to trigger an event:

function a()
{
var e = document.getElementById("storage");
e.innerHTML += "<p style='font-size:120%'>The time has come!</p>";
}
function term()
{
var now = new Date();
var hours = document.getElementById("hours").value;
var minutes = document.getElementById("minutes").value;
var seconds = document.getElementById("seconds").value;
var term = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hours, minutes, seconds, 0);
setTimeout(a, term - now);
var e = document.getElementById("storage");
var diff = Math.round((term.getTime() - now.getTime()) / 1000);
e.innerHTML += "<p><p>Will occur in " + diff + " seconds...</b></p>";
}

Demonstration

Enter : Hour Minutes Seconds

To help you, here are the current date and time:

Events will come here...

Back to the tutorial setTimeout and setInterval.