How to make the page go back to the beginning after a certain time?

Issue

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!

Solution

This will check every 5 seconds if any activity has occurred, if not then trigger your page update.

var timestamp = Date.now();
var checkTime = null;

document.addEventListener('DOMContentLoaded', function(){
    checkTime = setInterval(doTimeout, 5000);
});


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


function doTimeout(){
    if (Date.now() - timestamp >= 5000){
    
    console.log("change page");
  
  }

}

Answered By – Phaelax z

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.