Does setTimeout continues even after changing page? - javascript

I have 2 pages, Home page and Edit page.
I used a function which will auto log out the user after a certain amount of time of inactivity.
The function is only used in Home page and not Edit page.
Below is the function code.
// Set timeout variables.
var timoutWarning = 10000;
var timoutNow = 30000;
var warningTimer;
var timeoutTimer;
// Start timers.
function StartTimers() {
console.log("Start TImer");
warningTimer = setTimeout("IdleWarning()", timoutWarning);
timeoutTimer = setTimeout("SignOut()", timoutNow);
$( "#timeout" ).dialog({
autoOpen: false
});
}
// Reset timers.
function ResetTimers() {
clearTimeout(warningTimer);
clearTimeout(timeoutTimer);
StartTimers();
$( "#timeout" ).dialog("close")
console.log("Reset TImer");
}
// Show idle timeout warning dialog.
function IdleWarning() {
$("#timeout").dialog({
autoOpen: true,
modal: true
});
}
I called out the function in the Home page by using
<body onload="StartTimers();" onmousemove="ResetTimers();">
<div id="timeout">
<h1>
Session About To Timeout</h1>
<p>
You will be automatically logged out in a while<br />
To remain logged in move your mouse
</div>
The timer works perfectly fine in the Home page, but after I switch to Edit page ( without the function basically an empty page), I will still get auto log out with or without moving the mouse.
Does that means that the function is still running even after I switch page? If so, is there anything I can do to stop the timer after I switched the page?
p.s I did tried adding in the function and call it in the Edit page, however, even after I kept on moving my mouse I will still get logged out which is why I assume that the function is still running after I switch page.
SOLVED : its working fine right now after I restart my browser. I believe I might have screwed up somewhere. I apologize to people who invested their time into this question. The answer to my question based on the comments/answers below is NO. setTimeout DOES NOT continues after changing page.

If the browser has fully loaded the second page, and that code isn't on it, that code won't run. That's assuming you're loading the second page 'traditionally' and not pulling it in via AJAX.
I would do the following things:
Put an alert("Code running") in the setTimeout function. That's a very simple way of telling you if the code is running or not.
Check the source code for your edit page. Make sure you haven't duplicated the code to that page too.

No, timeouts get deleted when you close/refresh the page (just like anything in JavaScript). So your bug must be something else.

Related

How to switch between different window.locations depending on answer to window confirm() method

I have a page that presents a test, where javascript sets a timeOut to abandon the page if the user waits too much (180") before giving an answer and pressing submit.
It has to be done for various reasons, and I cannot modify the committment.
After 180" on the page, so, currently the code goes back to a beginningpage.php where the user will have to re-enter its unique ID to continue the test.
This is the simple javascript code:
setTimeout(function () {
window.location.href= "beginningpage.php";
}, 180000);
Everything runs smooth. Now I need to modify the code to better manage the case. We assume that if the user has gone away, it will not be able to answer to an alert box. So let's say we push a confirm() after those 180".
How to write code so that - when the confirm() windows is displayed - if nobody clicks a confirm button (for let's say 30") the code automatically close the confirm window and leaves the page going back to beginningpage.php?
Otherwise, if the user is still at his desk and is simply wondering about the answer to give, he must be given the possibility to click "ok, I hurry up" to remain on the page for say another 60". That means that after the first displaying of the confirm window, the timeout must be set to a different deadline, not 180000 as before but 60000.
Maybe the idea of using different window.locations.href is not the right one.
How could be the code to accomplish everything I need as above explained?
Just don't use a confirm box... Show a div with two buttons after 180 seconds and then start counting your 30 seconds.
So let's say we push a confirm() after those 180".
How to write code so that - when the confirm() windows is displayed - if nobody clicks a confirm button (for let's say 30") the code automatically close the confirm window and leaves the page going back to beginningpage.php?
You can't. confirm, alert, and promopt are 1990s holdovers with stop-the-world behavior. (Mostly. Browsers are eroding that slowly over time.) That means none of your JavaScript code can run while the archaic window is showing.
Instead, switch to using modern alerting techniques (showing a "modal" div, etc.) so that your JavaScript code can use setTimeout to give up after the relevant amount of time.
You can never achieve this with alert or confirm because they block further js execution till the popup is active.
You need a custom modal with html element and a js function
All you have to do is call clearTimer for auto-page reload based on the response from custom confirm modal.
var x = document.getElementById("stopReloadBtn")
var reloadTimer
setTimeout(function() {
x.style.display = "block"
reloadTimer = setTimeout(function() {
window.location.href = "beginningpage.php"
}, 5000)
}, 5000);
function stopReload(){
clearTimeout(reloadTimer)
x.style.display = "none"
}
<button id="stopReloadBtn" style="display: none" onclick="stopReload()">Still Here?</button>
I have reduced the timers to 5 sec in this code. A button will appear after 5 sec. After which you will have 5 sec to click this button else the page will reload.

Jquery Mobile - Javascript persisting when navigating to another page

Hey guys I have a javascript function that keeps persisting even when navigating to another page (single page templates not multipage) in Jquery Mobile
<script type="text/javascript">
setInterval("window.location.reload();", 5000);
</script>
How do I ensure that this only occurs on the page from which it is called rather than it calling it on every page I link to with ajax based navigation?
I am using Jquery Mobile 1.2
Bind it to the page where you want it to occur. Replace $('.selector') with pageID, e.g. $('#home'). You could also be more specific $('div[data-role="page"]#PageID').
// Trigger interval
$('.selector').bind('pageinit', function () {
setInterval("window.location.reload();", 5000);
});
// Stop interval when navigating away
$('.selector').bind('pagehide', function () {
clearInterval();
});
How do I ensure that this only occurs on the page from which it is
called rather than it calling it on every page I link to with ajax
based navigation?
Don't call it? Currently your code is set up to always run when it's included on the page. Either don't include it or prevent it from running in some other way (such as an if-statement).
You could clear the interval just before you navigate.
First you need to get a reference to the interval when you create it:
var intervalRef = setInterval("window.location.reload();", 5000);
Then you can clear it like this:
clearInterval(intervalRef);
// Navigate
Just cancel your timeout when the other page loads, or when the current page exits (the other page loads in ajax so the timed interval stays up).
// trigger
myInterval = setInterval("window.location.reload();", 5000);
// stop
clearInterval(myInterval);

Website: Detect when I arrive somewhere because of History Navigation

I have a page where I show a throbber when I navigate away from the page. Like <a onclick="throbber.show()"> on every link. When I now navigate back in Firefox, the throbber is still shown.
Is there any javascript event that is fired to the arriving webpage when I click back? Or one that is fired just when the webpage is changed to the new one? Or can I make my throbber more intelligent?
Thanks for any input!
put this in your html:
<form name="_browser"><input id="checker" value="1" type="hidden"></form>
and also this javascript:
function cacheCheck()
{
var checker = document.getElementById("checker");
if (checker.value == 2) return true;
checker.value = 2;
checker.defaultValue = 2;
return false;
}
function cacheReload()
{
if (cacheCheck()) location.reload(true);
}
and then call cacheReload when your page loads:
<body onload="cacheReload()">
Dldnh's answer inpired me to do some tests. I suspected that the body.onload() event would be called when going back and forth. So I created a simple testpage and found out that this is true in Firefox 10, IE7, IE 8, IE 9 and Chrome 17. Also jQuery(document).ready() will be called.
The very simple solution for hidind the throbber would therefore be either using
<body onload="hideThrobber()">
or using jQuery ready
jQuery(document).ready(function () {
hideThrobber();
};
to hide the throbber then. I implemented this and it seems to work fine on my page. Would be great if somebody with a similar problem could confirm this.
I also found this interesting Stackoverflow question. While it is a little outdated, the point that calling javascript on navigation back and forth slowing down the page is still true. But I would guess that todays JS-Engines are fast enough so this is not a real issue anymore.
If you can't turn off the throbber from the page you navigate to, there are a few things you can do. The trick is that the page will be left active, so you can start up some things before you leave, in the onclick. They aren't perfect though.
Start a timer. The timer will be running when you return to the page, so the timeout routine will be called, and you can switch the throbber off there.
Problem: if you set the timer interval too small, the timeout routine will be called before the user has actually left the page, and the throbber will stop. Or if you set the interval too large, it will take a while before the timeout routine kicks in after they have returned.
Add an event listener to the body that responds to the mousemove event, so that as soon as the user moves the mouse, the routine that turnes off the throbber will be called.
Problem: if the user clicks the browser's Back button, the mouse will be outside the window when the page is redisplayed, so the throbber will remain visible until the user moves the mouse into the window.
So, take your pick. Or do both. Just remember to clean up afterwards - stop the timer, remove the event listener.

Problem with Jquery, setInterval inside a Facebook iframe

I'm building a simple Facebook tab. I have two tabs that change every 3 seconds with with the help of setInterval and JQuery until the user interacts with them. Which them cancels the switching.
$(document).ready(function() {
$('#item2').hide();
$('li#tab1').addClass('selected');
var timer = setInterval(function () {
$('div.item').fadeToggle('fast')
$('li.tab').toggleClass('selected') ;
}, 3000);
$(window).blur(function(){
clearInterval(timer)
})
// setup. Set the first tab to selected
$('li.tab').click(function(event) {
clearInterval(timer);
$('li.tab').toggleClass('selected')
$('div.item').fadeToggle('fast')
});
});
This works fine... mostly. The problem occurs when I lose focus on the page for a while ( 2-3 minutes ) and switch back, the tabs switch back and forth very fast for a while before returning to normal. I am able to fix this issue if NOT in an iframe with:
$(window).blur(function(){
clearInterval(timer)
})
which just stops the switch altogether. But this does not work when the page is inside a iframe on Facebook. Can anyone suggest a solution?
Try using setTimeout instead of setInterval.
function doStuff(){
//do some stuff
setTimeout(doStuff, timeout);
}
setTimeout(doStuff, timeout);
This way, you only have one iteration going in the background, so it'll flash once immediately when the user switches back to the page (hopefully fast enough that he doesn't notice).

How to keep timer running when alert is displayed in javascript

I am having a Javascript function which displays timer.
Now,when timer reaches 2 minutes, I want to display a alert and continue my timer function.
But,my timer function stops till user clicks 'Ok' and then resumes from 1:59 secs.
Can anyone tell me how to keep the timer function running while popup box is displayed?
Here's my function to display timer.
var minutes=5;
var seconds=59;
function time_display(){
if(minutes==2 && seconds==0){
setTimeout('display_time_alert_two_minutes_left()',100);
}
if (seconds<=0){
seconds=59;
if(minutes>0)
minutes-=1;
}
else
seconds-=1;
$('time_left_in_minutes').innerHTML = minutes+"."+ ljust_zero(seconds);
setTimeout("time_display()",1000);
}
time_display();
and this is my alert function.
function display_time_alert_two_minutes_left(){
alert('Two minutes left');
}
Alert is a blocker, use custom javascript popups like lightbox,lytebox,jquery dialog,fancybox etc.
Or you can simply show/hide a floating div. This will solve the problem of your timer
getting stuck, and also enhance your user experience.
How about you use something thats no so intrusive, something like this
As alert() stops the rest of the javascript code executing, it would be better to use something that doesn't require an imperitive style of incrementing time.
How about you actually use the time/date functionality, which will 'keep counting'?
Edit : This will stop the web page updating when you call alert() but it will keep counting fine whilst an alert is open.

Categories