Reputation: 328
I need to check my visitor tracker so I entered this in the chrome console with the setting set to preserve the log:
i = 0;
while (i<4)
{
location.reload();
window.alert(i);
i++;
}
The alert box pops pops up 4 times with the values ( 0, 1, 2, 3) and I also get the result:
3
Navigated to "url of website"
The result and the alert box show that the code runs till the end but why does the page reload only once?
Please don't be harsh.
Upvotes: 0
Views: 2769
Reputation: 176
When you reload your page, all javascript code that you have written is lost. In your code, the location.reload()
function is executed before alert()
, but I suspect because it takes time for the location.reload()
function to fully execute, it still has plenty time executing the alert()
function, and also all the other iterations aswell, which leads to the while loop to finish before the page has reloaded.
location.reload()
probably falls under the category of asynchronous functions, which means the function starts executing and keeps running in the background. All code that follows a asynchronous function is immediately executed, regardless of whether the asynchronous function has finished by then or not.
If you want to keep track of the visitor count, make use of some php and save the data in a database.
UPDATE:
Put this code into a .html file and open it. Reload it as many times as you wish, and check the currentClicks
variable in your console.
<!DOCTYPE html>
<body>
<script>
var currentClicks = localStorage.getItem("clickCount");
currentClicks++;
localStorage.setItem("clickCount", currentClicks);
</script>
</body>
</html>
Upvotes: 1
Reputation: 13682
I suspect that location.reload()
sets up a request to reload the page, but one that does not take place immediately. It's probably waiting for the current code to finish running, and is then dispatched later. After it's dispatched once, the rest of the pending reloads are lost.
Upvotes: 0