Function js run at a certain time

1

Sirs, I have a question, is there any method that for example executes at a certain time?

I would like when it was 0h the page would update automatically, so I would save some cookie to inform that day has already been updated ..

    
asked by anonymous 06.07.2017 / 13:21

3 answers

2

I do not think it's possible to build and persist a cookie with just pure HTML and Javascript.

The most root solution for doing something every day at midnight, just with Javascript, would be something like:

var dezSegundos = 10000; // dez segundos em milissegundos
var quinzeSegundos = 15000;
var verificaHora() {
    var agora = new Date();
    var hoje = new Date(agora.getFullYear(), agora.getMonth(), agora.GetDate());
    var msDesdeMeiaNoite = agora.getTime() - hoje.getTime();
    if (msDesdeMeiaNoite < quinzeSegundos) {
        // Aqui você executa sua lógica
    } 
}
setInterval(verificaHora, dezSegundos);

Explanation: Code runs every five minutes - use setInterval rather than setTimeout for the code to continue running for several days in a row. So if it's the first time it runs in a day, it does something you've implemented.

To complete, such as setInterval is not guaranteed to run exactly in the instant for which has been programmed , we give it a five-second slack to run.

    
06.07.2017 / 13:35
1

This function here works perfectly for this, just switch to the desired times and use the reload() function to refresh the page.

var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
if (millisTill10 < 0) {
     millisTill10 += 86400000; // já passou das 10 da manhã, começa de novo.
}
setTimeout(function(){alert("São 10 da manhã!")}, millisTill10);
    
06.07.2017 / 13:26
0

The language does not have this type of freedom because it is very rare to use, what you can do is pick up the time: minute: second when the page loads, calculate how many ms are missing for the next day and put what you want within a setTimeOut.

    
06.07.2017 / 13:27