Refresh Page for interval using js

Viewed 107186

How can i refresh a page for every one minute using javascript. Note: I don't have control/option to edit HTML body tag (where we usually call onload function).

6 Answers

Here's the thing mate! (Point 4 is for this particular question)

1). If you want to reload the same windows over and over again then just execute
window.location.reload()

2). If you want to hard reload from the server then execute
window.location.reload(true)
(basically, just pass true as a boolean arg to the same line of code)

3). If you want to do the same job as point 1 and 2 with a time out. i.e. execute the reload after some time JUST ONCE, then execute
setTimeout("window.location.reload()",10000);
(this should execute on the window after 10 sec. JUST ONCE)

4). If you want to keep reloading the window with a certain timeout then execute
setInterval("window.location.reload()",10000);

(this should execute on the window after 10 sec. with 10 sec. for the interval)


Surely,there're many ways to pass a callback..
setInterval(function(){window.location.reload();},10000);
or
<code>
function call1(){
  location.reload(true);
}
setInterval(call1,10000);
</code>

Note:
-Have a look at MDN Guides for [setTimeout][1] and [setInterval][2] functions.
-Using the window object is optional but good to be used. (window is a global object and already available to your current window.)

If you don't want to edit the page, here's the trick. Open the console and write the below-mentioned snippet.

INTERVAL = 5    // seconds
STOP_AFTER = 15 // seconds

// Open the same link in the new tab
win1 = window.open(location.href);

// At every 5 seconds, reload the page
timer1 = setInterval(() => {
    win1.location.reload();
    console.log("Refreshed");
},INTERVAL*1000)

// Stop reloading after 15 seconds
setTimeout(() => clearInterval(timer1), STOP_AFTER*1000)
  1. Since you want to reload it, you can not simply write location.reload() since the console will be cleared once it is reloaded.
  2. Therefore, it will open a new tab with the same link. It will be easily able to control the 2nd tab using the console of the 1st tab.
Related