How can I make a new year script?

4

Well guys, I tried to do it but I could not. I want a javascript code that automatically activates 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>');
}
    
asked by anonymous 31.12.2016 / 14:48

1 answer

6

Use new Date() with .getFullYear() , which returns the year. If it's 2017, run 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 this case, you need a loop ( setInterval ) to check every second if it's already new.

Save the range in a variable.

When it is new year, clearInterval() will be responsible for completing the loop, which will execute the function only once.

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

    
31.12.2016 / 14:56