How can I make a New Year script?

Asked

Viewed 126 times

4

Good guys, I searched how to do but could not. I want a javascript code that turns on automatically only after midnight. See the code:

var agora = new Date();
var anoNovo = new Date(2017, 0, 1, 0, 0, 0, 0);
var anoNovoMax = new Date(2017, 0, 1, 23, 59, 59, 0);
if(agora >= anoNovo && agora<anoNovoMax)
{
$('#musica').html('<audio autoplay="autoplay" controls="controls" style="display:none"> <source src="../fogos.mp3" type="audio/mp3" /></audio>');
$('#foguetes').html('<div class="fogos"></div>');
}

1 answer

6


Use the new Date() with the .getFullYear(), returns the year. If 2017, executes your code:

var interval;

function happyNewYear() {
  var date = new Date();

  if (date.getFullYear() == 2017) {
    console.log('Ano novo!!');
    
    clearInterval(interval);
  }
}

interval = setInterval(happyNewYear, 1000); // Executa a função a cada 1 segundo

In case you need a loop (setInterval) to check every second whether it is already new year.

Store range in a variable.

When it’s New Year’s, the clearInterval() will be responsible for ending the loop which will run the function only once.

Remember that since there is no connection to the server, this time will be the same as the user’s computer.

  • Thank you very much, it worked!

  • 1

    Mark the answer, @Hanz

Browser other questions tagged

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