How to trigger a function after a given date and time

Asked

Viewed 522 times

2

I’m trying to make a script that triggers a certain function after a date and time has passed. I have tried every way but can not, always give some error or bug. My last test I did so:

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

No problem if the function is triggered whenever the time has passed and the value of team should be the same as the example.

  • 1

    This date format is mm/dd/yy or dd/mm/yy? As far as I know, the builder of Date receives the parameter in the first format.

  • That’s what I was missing, but I’ve got it here

1 answer

7


The way you wrote 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());

Which would be simpler and faster, since it would only perform the function at the right time.

  • It didn’t work here =/

  • ha ready, it worked now the/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.