Fullbringa
Fullbringa

Reputation: 59

javascript / html auto refresh button

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>

Upvotes: 0

Views: 1649

Answers (2)

Jonel Zape
Jonel Zape

Reputation: 42

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

Upvotes: 0

Harion
Harion

Reputation: 225

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

Upvotes: 2

Related Questions