Javascript page reload prevention
I use this javascript to automatically refresh the page every 30 seconds.
<script type="text/javascript"> window.setTimeout(function(){ document.location.reload(true); }, 30000); </script> I need to give users the option to disable this feature at any time before reloading the page.
Note. This is for the admin panel and not for the public website, and the requirement from the client is that the page automatically refreshes, with the option to stop the refresh before it happens by clicking the button.
Is there any way to achieve this ... Is it .. disable javascript before executing it?
clearTimeout (): Cancels the timeout previously set when calling
setTimeout().
You are looking for clearTimeout() :
var refresh = window.setTimeout(function(){ document.location.reload(true); }, 30000); $('body').on('click', '#my-button', function(){ clearTimeout(refresh); }) Hope this helps.
Below is a code that will last every 500 ms until you press a button to stop it. Just replace 500 with the time you need and replace console.log with whatever you want to run. Hope this helps!
let auto_refresh_active = true; const refresh = () => { window.setTimeout(e => { console.log('Hey, I am running! Click the button to stop me!') if(auto_refresh_active == true) refresh(); }, 500) } refresh(); document.querySelector('button').addEventListener('click', e => auto_refresh_active = false); <button>stop running</button>