0

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!

5 Answers5

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()
});
user17517503
  • 155
  • 11
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.

N80
  • 1
  • 3
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.

Jonas V
  • 668
  • 2
  • 5
  • 20
0

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");
  
  }

}
Phaelax z
  • 1,814
  • 1
  • 7
  • 19
0

call setTimeout once then call clearTimeout if there are touch or click event

document.addEventListener('DOMContentLoaded', function() {
  var timeout = setTimeout(function() {
    console.log('page will go back!');
  }, 3000);

  ["click", "touchstart"].forEach(function(event) {
    document.addEventListener(event, function() {
      clearTimeout(timeout)
      console.log('will not go back')
    });
  })
});
uingtea
  • 6,002
  • 2
  • 26
  • 40