Reputation: 5001
I have simple function;
setTimeout(function(){ alert('hello');
//Business stuffs..
location.reload();
eval(localStorage.getItem('mysc'))},5000)
after open in a browser(chrome or firefox) I type this;
localStorage.setItem("mysc","setTimeout(function(){
//Business stuffs...
location.reload();
eval(localStorage.getItem('mysc'))
},5000)");
After that once I type;
eval(localStorage.getItem('mysc'))
I want this function executes in same browser window forever.. or till close the browser.. but as you guess, it only works once. How can I achieve this ?
Upvotes: 3
Views: 2374
Reputation: 15240
You should create the timer on page load, and reload the page in the callback. When the page reloads, the timer will be re-created. This will "recursively" reload the page every 5 seconds.
<html>
<head>
<script type="text/javascript">
console.log('page loaded, waiting...');
setTimeout(function () {
console.log('reloading');
location.reload();
}, 5000);
</script>
</head>
</html>
As far as I know, there is no way to achieve this if you don't control the page you want to reload (i.e., using Dev Tools or console APIs). It's impossible to attach a script to execute on the next page load, and any active timers are cleared when the current page unloads. A browser extension is probably the way to go; for example, Content Scripts can be used to achieve this in Chrome.
Upvotes: 2