Why Refresh a Page with Code at All?
\n\nImagine: you are writing a chat, an online game, or a feedback form. The user sent data — and everything froze. To see the result, they have to press F5 or click the browser button. Inconvenient, right?
\n\nNow imagine that the page refreshes itself — as soon as the action is completed. Magic? No, just pure JavaScript and a couple of lines of code. That's exactly what we're going to talk about today.
\n\nThe topic seems simple at first glance, but even experienced developers sometimes confuse the location.reload() and window.location.href methods. We'll cover all the options, pitfalls, and best practices. Let's go!
The Main Character: location.reload()
\n\nThe most popular and correct way to refresh a page via JavaScript is the location.reload() method. It does exactly what it says on the tin: reloads the current document.
// The simplest option\nlocation.reload();\n\nBut there is a nuance. This method takes one optional parameter — a boolean value forceGet.
- \n
location.reload()— reloads the page using the browser cache if possible. \n location.reload(true)— forces a load from the server, ignoring the cache. \n
The difference is noticeable when you work with dynamic data. If you need to guarantee getting the latest version of the page — use true.
Comparison: reload() vs window.location.href
\n\nOn Stack Overflow, people often ask: "Can I just assign window.location.href = window.location.href?"
Short answer: you can, but it's a crutch. Long answer — see the table.
\n\nComparison table of page reload methods
\n\n| Method | \nBehavior | \nUses cache | \nRecommended | \n
|---|---|---|---|
location.reload() | \n Reloads the page | \nYes (by default) | \n✅ Yes | \n
location.reload(true) | \n Forced reload from server | \nNo | \n✅ Yes | \n
window.location.href = window.location.href | \n Redirects to the same page | \nYes | \n⚠️ With caution | \n
window.location = window.location | \n Same thing, shorter | \nYes | \n⚠️ With caution | \n
history.go(0) | \n Navigates to the current page in history | \nYes | \n❌ Deprecated | \n
As you can see, location.reload() is the most reliable and predictable method. Other options may work inconsistently across different browsers.
Automatic Refresh at a Set Interval
\n\nSometimes you need the page to refresh automatically — for example, to display exchange rates or server status. This is where setTimeout or setInterval come to the rescue.
Refresh 5 seconds after loading
\n\n// Wait 5 seconds, then reload\nsetTimeout(function() {\n location.reload(true);\n}, 5000);\n\nPeriodic refresh every 30 seconds
\n\n// Refresh the page every 30 seconds\nsetInterval(function() {\n location.reload();\n}, 30000);\n\nImportant: Do not overuse automatic reloading. If the page