Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Javascript Page Reload

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?

like image 457
ratherBeKiting Avatar asked Nov 03 '16 21:11

ratherBeKiting


Video Answer


2 Answers

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.

like image 194
Zakaria Acharki Avatar answered Oct 08 '22 13:10

Zakaria Acharki


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.

like image 41
Tom el Safadi Avatar answered Oct 08 '22 14:10

Tom el Safadi