Categories
JavaScript Answers

How to Automatically Reload a Page After a Given Period of Inactivity in JavaScript?

Spread the love

Sometimes, we want to automatically reload a page after a given period of inactivity on our web page.

In this article, we’ll look at how to automatically reload a page after a given period of inactivity with JavaScript.

Record the Time When There is Activity

We can listen to the mousemove and keypress events to let us listen for mouse and keyboard activities respectively.

Then we can record the time when the user last used the page in the event listener.

And then we can use that time to calculate how long ago when the user last used the page.

To do this, we write:

let time = new Date().getTime();
const setActivityTime = (e) => {
  time = new Date().getTime();
}
document.body.addEventListener("mousemove", setActivityTime);
document.body.addEventListener("keypress", setActivityTime);

const refresh = () => {
  if (new Date().getTime() - time >= 60000) {
    window.location.reload(true);
  } else {
    setTimeout(refresh, 10000);
  }
}

setTimeout(refresh, 10000);

We have the time variable which has the timestamp in milliseconds as its initial value.

Then we have the setActivityTime event listener which we use to set the time at which the user last used the page.

We listen to the mousemove and keypress events and use setActivityTime as the event listener to record when the user last interacted with the page.

Then we have the refresh function that checks when the user last interacted with the page.

If the time is more than 60 seconds, then we call location.reload to reload the page.

Otherwise, we call refresh again to check again in 10 seconds.

Now the page should refresh if it hasn’t been interacted with for more than 60 seconds.

Conclusion

We can record the latest time of when the user interacted with a page.

Then we can check how long ago was the last page activity and refresh based on the time comparison if required.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

2 replies on “How to Automatically Reload a Page After a Given Period of Inactivity in JavaScript?”

Leave a Reply

Your email address will not be published. Required fields are marked *