5

I am using this javascript to auto refresh a page every 30 seconds.

<script type="text/javascript">
    window.setTimeout(function(){ document.location.reload(true); }, 30000);
</script>

I need to give users an option to disable this function at any time before the page is reloaded.

Note: this is for an admin panel, not a public website, and the requirement from the client is that the page auto refreshes, with an option to stop the refresh before it happens by clicking a button.

Is there any way to achieve this... That is.. disable the javascript before it executes?

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
ratherBeKiting
  • 275
  • 5
  • 14

4 Answers4

8

clearTimeout() : Cancels a timeout previously established by calling setTimeout().

You're searching for clearTimeout() :

var refresh = window.setTimeout(function(){ document.location.reload(true); }, 30000);

$('body').on('click', '#my-button', function(){
    clearTimeout(refresh);
})

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
3

Do the following:

reload = window.setTimeout(function(){ document.location.reload(true); }, 30000);

Or, if using jQuery,

$("#non-reload-button").click(function(){
  clearTimeOut(reload)
});
3

Do it this way:

var myVar;

function myFunction() {
    myVar = window.setTimeout(function(){ document.location.reload(true); }, 30000);
}

function myStopFunction() {
    clearTimeout(myVar);
}

You just have to call the myStopFunction in order to stop the auto reload.

Tom el Safadi
  • 6,164
  • 5
  • 49
  • 102
2

Below is code that will continue to execute every 500ms until you click the button to stop it. Just replace the 500 with the time you want and replace the console.log with what ever operation you wish 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>
ONMNZ
  • 322
  • 3
  • 8