Prevent Javascript Page Reload - javascript

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?

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.

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.

Do the following:
reload = window.setTimeout(function(){ document.location.reload(true); }, 30000);
Or, if using jQuery,
$("#non-reload-button").click(function(){
clearTimeOut(reload)
});

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>

Related

JavaScript Doesn't do anythign when I click button

var timeout = false;
setTimeout(function(){
timeout = true;
}, 3000);
$("#waitForClick").on('click',function(){
if(!timeout)
alert("Please comment this website in comments of games.");
else
window.location = "step3.php";
});
What it should do is wait 3 seconds and alert them a message before redirecting to the next page.
Try putting the setTimeout inside of the on click function... I'm assuming you want to wait three seconds AFTER you click?
Try this, for some reason jsfiddle isn't letting me save anything at the moment.
$(document).ready(function() {
$('#waitForClick').on('click', function(){
setTimeout(function() {
alert("Please comment this website in comments of games.");
window.location = "step3.php";
}, 3000);
});
});
I try to put your code inside a document.ready... and it's works:
$(document).ready(function () {
var timeout = false;
setTimeout(function(){
timeout = true;
}, 3000);
$("#waitForClick").click(function(){
if(!timeout){
alert("Please comment this website in comments of games.");
}else{
window.location = "step3.php";
}
});
});
Your element was not loaded when you called.
Please do not forget to import jQuery!
(Sorry for my bad english)

location.assign not working in IE

I wrote a small jquery code to redirect to google.com after 2 seconds on pressing a button. The code works fine in Firefox, google chrome but not in the Internet Explorer.
I believe the location.assign function is not working since it is the one that is supposed to redirect to another url and all other functions like alert are working but not this one.
The code is as follows:
<script type="text/javascript">
$(document).ready(function(){
$(".prize_select").click(function(){
var timer = setInterval(redirect,2000);
function redirect()
{
location.assign("http://www.google.com");
timer = clearTimeout(timer);
}
});
});
</script>
I would also say that I have already tried these function:
location.assign
window.location
window.location.href
but none of them seems to work in Internet Explorer
You need setTimeout(), not setInterval(). Also, you need location.href, not just window.location. This script says, "When .prize_select is clicked, redirect to "cnn.com" after 2000 ms.
$(document).ready(function() {
$(".prize_select").click(function() {
window.setTimeout(function() {
location.href = 'http://www.cnn.com';
}, 2000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button class="prize_select">Click me!</button>
Declare the function before using it. e.g.
var timer;
var redirect = function(timer) {
location.assign("http://www.google.com");
timer = clearTimeout(timer);
};
timer = setInterval(function() { redirect(timer); }, 2000);
Update: now passes timer instance

Sequencing two action on a button click

Problem: I have a asp.net button and on click of that I am displaying another window using window.open() at the client side using <script></script>
"I actually, need a popup (alert message) to be displayed on my parent page where my button is located once the user closes the child window."
Couple of things I tried are as follows:
I tried using setTimeOut() to have a time out for some milliseconds. This does not work as the control is not waiting until the time out is complete. It just proceeds to execute next set of code.
I tried using setInterval() but for some reason it is not working for me. Below is the code snippet of that:
$(document).ready(function () {
$('#<%=btnClick.ClientID%>').bind('click', function () {
var newWindow = window.open("http://www.google.com/", "google", 'resizable=1,width=900,height=800,scrollbars=1', '_blank');
newWindow.moveTo(0, 0);
var test = setInterval(function (e) {
if (newWindow.closed) {
alert("HEYY");
clearInterval(test);
__doPostBack("<%= btnClick.UniqueID %>", "");
}
else {
e.preventDefault();
}
}, 5000);
});
});
.
I also tried making an ajax call to open the new window and make it async : false, it again did not help me.
Bring your window and timer variable out of scope of the event handler. You need to do a polling i.e. periodically keep on checking if the windows has been closed. Using setInterval to do a polling will do the job.
var newWin, pollTimer;
$('#btnId').bind('click', function () {
newWin = window.open("...", "...", "");
pollTimer = window.setInterval(function() {
if (newWin.closed) {
window.clearInterval(pollTimer);
callCodeWhenPopupCloses();
}
}, 5000);
});
function callCodeWhenPopupCloses() {
alert("Popup closed.");
...
}

Button to refresh page every second/minute etc?

I'm wanting a button that when clicked will refresh the current page after a specified amount of time.
I currently have:
<script type="text/javascript">
setTimeout(function reload(){
location = ''
},1000)
</script>
<button onclick="reload()">Reload</button>
However, that JUST reloads the page without even having to click the button. I'm wanting the button to execute the script, and also a button to STOP the page reload.
This should be really simple but I can't figure it out :(
******EDIT**********
I'd also like the script to run on an infinite loop after the button is clicked.
Your setTimeout is called on page load. You need to put it inside the reload() function:
function reload() {
setTimeout(function() {
window.location.reload();
}, 1000);
}
To make the timer run every x seconds and reload only a part of the page you would need to use setInterval and an AJAX request, something like this:
var timer;
function reload() {
timer = setInterval(function() {
$.post('foo.html', function(data) {
$('#bar').html(data);
});
}, 1000);
}
function clear() {
clearInterval(timer);
}
This should do the trick
<script type="text/javascript">
function reload(){
setTimeout(function(){location.reload()}, 3000);
}
</script>
<button onclick="reload()">Reload</button>
What you wrote is
window.setTimeout("location = ''"; ,1000);
You were saying execute this function after 1 second. You need to define the setTimeout inside the function. Also there is a built in method to reload the page. Call that instead of setting the location to a blank string.
function reload() {
setTimeout( function() {
window.location.reload(true);
},1000);
}
Now to cancel the timeout, you need to use clearTimeout(timeoutId); You get the timeoutId from the integer that the setTimeout returns when you call it.
var timer = null;
function reload() {
timer = window.setTimeout( function() {
window.location.reload(true);
},1000);
}
function cancelReload() {
if (timer) {
window.clearTimeout(timer);
}
timer = null;
}
AND you said you want it to keep running. That will require cookies or localstorage.
var timer = null;
function reload() {
localStorage.reload = true; //set localstorage so we know to fire it off again
timer = window.setTimeout( function() {
window.location.reload(true);
},1000);
}
function cancelReload() {
if (timer) {
window.clearTimeout(timer);
}
timer = null;
localStorage.removeItem("reload"); //remove the key in localstorage
}
if (localstorage.reload) { //check localstorage to see if key is set
reload();
}
You need to wrap the whole thing in another function and call that from the button click

Jquery timeout code not re-running after first time user extends session

I wrote a Jquery function that blacks out the screen after a certain amount of inactivity, creates a pop-up that allows the user to click a button to stay logged in, and logs them out (closing the application window) if they do not respond in time.
The environment is ASP.NET (VB). We don't technically use master pages, but we do have a parent page in which our header, footer and nav reside, and my Jquery code is called from that window, loaded via an IFrame.
I've got a function in the child window that reports activity (currently keydown, mousedown and blur) to the parent window, and resets the timer. My code seems to be working fine, except in one scenario. If the user is prompted with the timeout warning, and then they click the button to continue their session, if they take no action on the page (mouseclick, keydown, etc.) then the timeout code is not running a second time.
Here is my main jquery function:
function pop_init() {
// show modal div
$("html").css("overflow", "hidden");
$("body").append("<div id='popup_overlay'></div><div id='popup_window'></div>");
//$("#popup_overlay").click(popup_remove); // removed to make sure user clicks button to continue session.
$("#popup_overlay").addClass("popup_overlayBG");
$("#popup_overlay").fadeIn("slow");
// build warning box
$("#popup_window").append("<h1>Warning!!!</h1>");
$("#popup_window").append("<p id='popup_message'><center>Your session is about to expire. Please click the button below to continue working without losing your session.</center></p>");
$("#popup_window").append("<div class='buttons'><center><button id='continue' class='positive' type='submit'><img src='images/green-checkmark.png' alt=''/> Continue Working</button></center></div>");
// attach action to button
$("#continue").click(session_refresh);
// display warning window
popup_position(400, 300);
$("#popup_window").css({ display: "block" }); //for safari using css instead of show
$("#continue").focus();
$("#continue").blur();
// set pop-up timeout
SESSION_ALIVE = false;
window.setTimeout(popup_expired, WARNING_TIME);
}
Here is the code from the parent window:
<script language="javascript" type="text/javascript">
var timer = false;
window.reportChildActivity = function() {
if (timer !== false) {
clearTimeout(timer);
}
//SESSION_ALIVE = true;
timer = window.setTimeout(pop_init, SESSION_TIME);
}
</script>
Here is the code from the child window:
<script type="text/javascript">
$(document).ready(function() {
window.parent.reportChildActivity();
});
</script>
<script type="text/javascript">
$(document).bind("mousedown keydown blur", function() {
window.parent.reportChildActivity();
});
The last script runs in a file (VB.NET ascx file) that builds the header/menu options for every page in our system.
The last line in the pop_init function clearly should be re-starting the timer, but for some reason it doesn't seem to be working.
Thanks for any help and insight you may have.
Forgot to add my code for the session_refresh function:
function session_refresh() {
SESSION_ALIVE = true;
$(".buttons").hide();
$("#popup_message").html("<center><br />Thank you! You may now resume using the system.<br /></center>");
window.setTimeout(popup_remove, 1000);
$("#popup_window").fadeOut("slow", function() { $('#popup_window,#popup_overlay').trigger("unload").unbind().remove(); });
var timer = false;
window.reportChildActivity = function() {
if (timer !== false) {
clearTimeout(timer);
}
timer = window.setTimeout(pop_init, SESSION_TIME);
}
}
use this: http://www.erichynds.com/jquery/a-new-and-improved-jquery-idle-timeout-plugin/
You need to restart your timer after the user clicks the button.
Well, I seem to have fixed the problem by changing this:
var timer = false;
window.reportChildActivity = function() {
if (timer !== false) {
clearTimeout(timer);
}
timer = window.setTimeout(pop_init, SESSION_TIME);
}
to this:
if (timer !== false) {
clearTimeout(timer);
}
timer = window.setTimeout(pop_init, SESSION_TIME);
I didn't need to re-declare the reportChildActivity function as I was.

Categories