Button to refresh the page every second / minute, etc.?

I want a button that, when clicked, will refresh the current page after a certain time.

I currently have:

<script type="text/javascript">
  setTimeout(function reload(){
    location = ''
  },1000)
</script>

<button onclick="reload()">Reload</button>

      

However, JUST reloads the page without even pressing a button. I want a button to execute the script as well as a button to stop the page reloading.

It should be very simple, but I can't figure out :(

****** EDIT **********

I would also like the script to run in an infinite loop after the button is pressed.

+3


source to share


4 answers


Yours setTimeout

is called on page load. You have to put it in a function reload()

:

function reload() {
    setTimeout(function() {
        window.location.reload();
    }, 1000);
}

      



To make the timer start every x seconds and reload only part of the page, you will need to use setInterval

an AJAX request too, something like this:

var timer;
function reload() {
    timer = setInterval(function() {
        $.post('foo.html', function(data) {
            $('#bar').html(data);
        });
    }, 1000);
}

function clear() {
    clearInterval(timer);
}

      

+6


source


This should do the trick



<script type="text/javascript">
  function reload(){
    setTimeout(function(){location.reload()}, 3000);
  }
</script>

<button onclick="reload()">Reload</button>

      

+2


source


What you wrote

window.setTimeout("location = ''"; ,1000);

      

You said you would execute this function in 1 second. You need to define setTimeout inside the function. There is also a built-in method to reload the page. Call this instead of giving the location on an empty line.

function reload() {
    setTimeout( function() {
        window.location.reload(true);
    },1000);
}

      

Now, to cancel the timeout, you need to use clearTimeout(timeoutId)

; You get the timeoutId from an integer that setTimeout returns when you call it.

var timer = null;
function reload() {
    timer = window.setTimeout( function() {
        window.location.reload(true);
    },1000);
}

function cancelReload() {
    if (timer)  {
        window.clearTimeout(timer);
    }
    timer = null;
}

      

And you said you wanted him to keep working. This will require cookies or localstorage.

var timer = null;
function reload() {
    localStorage.reload = true;  //set localstorage so we know to fire it off again
    timer = window.setTimeout( function() {
        window.location.reload(true);
    },1000);
}

function cancelReload() {
    if (timer)  {
        window.clearTimeout(timer);
    }
    timer = null;
   localStorage.removeItem("reload");  //remove the key in localstorage
}

if (localstorage.reload) {  //check localstorage to see if key is set
    reload();
}

      

+1


source


You need to wrap the whole thing in another function and call this on a button click

0


source







All Articles