How to trigger a function after a certain date and time

2

I'm trying to make a script that triggers a certain function after a date and time has passed. I have tried in all ways but I can not, always with some error or bug. My last test did so:

var time = '08/03/2014 23:45';
setInterval(function() {
    if ( Date(time) <= Date() ) {
        document.body.innerHTML += 'Ring ring! ♪♫ <br>';
    }
}, 1000);

There is no problem if the function is fired whenever the time has passed and the time value should be the same as the example.

    
asked by anonymous 09.03.2014 / 03:52

1 answer

7

The way you wrote it best would be to compare numerical values:

// Pega o valor numérico da data e hora:
var time = (new Date('08/03/2014 23:45')).getTime();
setInterval(function() {
  // Compara com o valor atual:
  if (time <= Date.now()) {
    document.body.innerHTML += 'Ring ring! ♪♫ <br>';
  }
}, 1000);

But you could also write more optimally, like:

// Pega o valor numérico da data e hora:
var time = (new Date('08/03/2014 23:45')).getTime();
// Executa a função quando no tempo marcado:
setTimeout(function() {
  document.body.innerHTML += 'Ring ring! ♪♫ <br>';
}, time - Date.now());

What would be simpler and faster, since it would only run the function at the right time.

    
09.03.2014 / 04:12