Ways To Refresh A Page In JavaScript

Introduction

In today's article, we will see how you can refresh the page on the client side only. Below I've listed the multiple ways with examples by which we can refresh the page according to your need. We can use any of the below.

  • location.reload()
  • Refresh Using Button -
  • using setTimeout() -
  • History API- history.go()
  • Meta Refresh

location.reload()

The location.reload() method reloads the current URL like the refresh button of the browser. It can be accessed via document.location or window.location.

window.location.reload();
document.location.reload();

Refresh using Button

We can create a button, and onClick event of this button, we can reload the page.

<button type="button" onclick="window.location.reload()">Refresh Me</button>

Using setTimeout()

The setTimeout() calls a function after a number of milliseconds. In the below example, it will reload the page every 2sec. We can define any time period in milliseconds.

setTimeout(()=>{
window.location.reload();
},2000);

History API

History.go() method loads a specific page from the browser session history. We can use any of the below statements to reload the same page.

history.go();
history.go(0);

We can also move backward and forward a page using this History API.

history.go(-1);        //To move back one page
history.go(2);         //To move forward two pages

Meta Refresh

Let's first discuss Meta tags. Meta tags define metadata about the HTML document. The meta tags don't appear on the page. It's just placed in the document source code that holds a piece of additional information about the document. 

Meta Refresh automatically reloads the current webpage after a set interval of time. The following code automatically refreshes after every 5 sec.

<meta http-equiv="refresh" content="5"/>

You can also redirect to another page using Meta refresh

<meta http-equiv="refresh" content="0;url=https://www.c-sharpcorner.com/"/>

This example will redirect to another page immediately as soon you land on the page it redirects.

Conclusion

So these are the multiple ways, and you can use any of the above as per your requirement to reload/refresh the page.

Also, we can do many various things using these APIs that I'll cover in another Article, till then Happy Coding :) 


Similar Articles