0

I would like to build a webpage button which if clicked reloads the webpage every x seconds (i.e. 5 seconds = 5000 ms). The Problem is that my function gets executed once after 5 seconds, but wont continue to auto refresh after the button was clicked. It always waits for the next button click. In theory I know that after the click my function has to be called every x seconds, but I simply don't know how to implement this. This is how far i got:

<html>
<head>
</head>
<body>
    <button id = "btn-reload">Automatischer Reload der Seite</button>
    <script>
        const btnReload = document.getElementById("btn-reload");

        btnReload.addEventListener("click", function(){
            setInterval(function(){
            location.reload()}, 5000);

        });
    </script>
</body>
</html>
3
  • well, you might want to set something in the localStorage that auto-refresh is enabled, and validate that when you are loading your webpage, and in case it is enabled, start the interval Commented Jan 27, 2020 at 9:52
  • I think you are tying to do something like real-time notifications, setInterval is the worst solutions for this, it may cause many problems. read more about socket or signal-R . Commented Jan 27, 2020 at 9:52
  • location.reload will reload the page and set all html control with its initial state. Commented Jan 27, 2020 at 10:17

2 Answers 2

2

While you refreshing page all state is cleared so also interval not exist. To make it work you need something which will save the state between refresh for example local storage: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Sign up to request clarification or add additional context in comments.

Comments

0

You can use URL as your flag if auto refresh is enabled.

Example your-url.com?autorefresh=true

on window load check this flag is set or not to run your auto refresh feature

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.