Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
How to make the page go back to the beginning after a certain time?

I'm creating a webpage and I decided to try to get you back to the start automatically if it takes a certain amount of time without clicking the screen. I tried to do so but when I enter the page no matter how much it touches the screen the time does not reset and the alert appears anyway. The webpage is also loading and does not load all the content. Here is the code I currently have:

var startTime = new Date();

document.addEventListener('DOMContentLoaded', function(){

    var seconds = 1;

    while (seconds < 5) {
        endTime = new Date();

        var timeDiff = endTime - startTime; //in ms
        // strip the ms
        timeDiff /= 1000;
    
        // get seconds 
        var seconds = Math.round(timeDiff);
        console.log(seconds + " seconds");
        setTimeout(() => {}, 1000); // Like time.sleep
    }

    alert("Touch the screen!")
})

document.addEventListener("click", function() {
    console.log("Hello")
    startTime = new Date()
});

Thank you!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The setTimeout function is an async function, so is not block the main thread.
You should use

let startTime=new Date();
setInterval(function() {
 let currentTime=new Date();
 let timeDiff=(currentTime-startTime)/1000;
 if(timeDiff>5) {/*code to scroll up the page*/}
  },200) //it checks every 200 millisecodns the time
document.addEventListener("click", function() {
    console.log("Hello")
    startTime = new Date()
});
about 4 years ago · Juan Pablo Isaza Relatório

0

The "DOMContentLoaded" is fired once the HTML document is loaded, this often means that it is before css and images are loaded to the page, which could explain why your page isn't fully loading. I don't see any logic which is resetting the timer once the page is clicked, you should have an on click event listener which will reset the timer, and move the timer variable outside of a level of scope so that both event listeners can use it.

about 4 years ago · Juan Pablo Isaza Relatório

0

I think you have a misconception about how setTimeout works.
With setTimeout you can register a function that will be called after the indicated number of ms has passed.
The function you give it is a noop, so I'm guessing you imagine setTimeout to have a side effect. In this situation particularly, I'm guessing you are expecting setTimeout to halt the execution of the loop, but that isn't the case. If you are expecting it to work like a time.sleep function, thats not how it works, since after registering the callback, it simply moves on.

So the page isn't fully loading, because it has to continously run this while loop, and can't do anything else until it's done with that.

To get something more similar to time.sleep you can use async/await.

function sleep(ms){
  return new Promise(resolve => setTimeout(resolve, ms));
}

document.addEventListener('DOMContentLoaded', async function(){
    var seconds = 1;
    while (seconds < 5) {
        endTime = new Date();

        var timeDiff = endTime - startTime; //in ms
        // strip the ms
        timeDiff /= 1000;
    
        var seconds = Math.round(timeDiff);
        console.log(seconds + " seconds");
        await sleep(1000) 
    }

    alert("Touch the screen!")
})

In the above I defined a helper function, sleep, which creates a Promise, that simply resolves after the indicated amount of ms has passed.
To use this, the function using it has to be marked as async. That's why you can see the async keyword right before the function keyword in the addEventListener call.
Once that requirement is fulfilled, you can use the sleep function by adding the await keyword in front of it.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda