javascript browser timeout second timer - javascript

I am trying to set a session timeout with Javascript and looks like the alert is blocking the timer from starting. Here is my code:
var first_timer = 2 * 1000;
var second_timer = 8 * 1000;
var down = -1;
function initTimer() {
down = setTimeout(processTimeout, first_timer)
}
function processTimeout() {
down = setTimeout(logout, second_timer);
alert ("Timeout of first timer, timerid:" + down );
}
function logout() {
alert("You are logged out");
window.location = "http://www.google.com"
}
function clearTimer() {
if ( -1 != down )
clearTimeout(down);
alert("Restarting timer");
initTimer();
}
initTimer();
When I run the above, I see the second timer only starts after the first alert is dismissed. How can I make sure the second timer starts immediately after first timeout even if the alert is not dismissed?
Thx

The alert() function blocks everything else until it is dismissed. You can use whats known as a modal dialog to create your own alert style message that does not block.
jQuery UI has this feature.

It most probably depends on the browser you are using. I'm not experiencing the issue you describe with latest Firefox.
But still, the second timer alert box won't be shown until the first one is closed.
This is because JavaScript interpreters are not multi-threaded. But JavaScript itself is heavily asynchronous, especially on long delay requests such as timers, AJAX and animations. This is what sometimes gives the feeling of multi-threading.
Indeed, in your code sample, the second timer started as expected. When I dismiss the first dialog box, let's say, 10 sec after it appears, the second one is immediately shown.
Nonetheless, and it may be your question, it will never be shown before you dismiss the first alert because alert is a synchronous call. So that the main event loop won't get the control back until dismissed.
A workaround for this situation is to use "HTML" dialog boxes as those provide by Jquery-UI for example.

Related

How can one reset one variable in Javascript and playing an alert after a specific time?

I am trying to program a little game that should reload after 5 seconds and tell people that they were too slow. Moreover, the variable points should be reset, so that they can start from new.
With
setInterval(function(){
window.location.href = "javascript:window.top.location.reload(true)";
}, 5000);
the whole website is loaded and people have to begin from scratch. The same happens when they press command+R.
I tried now to reset the variable points and show the alert that they were too slow.
setInterval(function(){
alert("You were too slow!");
points = 0;
}, 5000);
If I use this code, then the alert keeps on popping up very quickly. How can I reset everything and only get the alert every 5 seconds?
Depending on the browser the internal timer will continue running while the modal is displayed like in Firefox, or freez like in Chrome. So in Firefox if the modal stays open longer then 5 seconds, then the next one will be showed immediatily after the current one is closed.
There are only rare cases where you really want to use setInterval even if you have events that happen in regular intervals you most of the time should use setTimeout instead.
var roundTimeoutTimer;
function tookToLong() {
alert("You were too slow!");
points = 0;
}
function startTask() {
roundTimeoutTimer = setTimeout(tookToLong, 5000)
}
function finishedTask() {
clearTimeout(roundTimeoutTimer)
}

window.focus doesn't work within http promise then

I try to make a focus on a new tab window , within callback (then function) of a http request and it doesn't work . i.e -
$http.get('').then(function () {
that.myWin.focus(); // isn't focusing
})
I did a demo for that , press "Open" to open the tab and then press "Focus" to focus in this tab which doesn't work .
Here is another demo which isn't within then that works fine .
How to make the focus function to work well ?
EDIT :
I'm testing on Google Chrome.
I know this is kind of wiered issue, on which spent my couple of hours and actually I found something working.
While debugging I found that if, we tries to focus tab for than 1 sec of time, It doesn't focus the tab. So I assumed that in one second I should access that.myWin object, otherwise after 1sec nothing happens with tab focusing.
$scope.focus = function() {
//maintained flag for checking promise completed or not.
var promiseResolved = false; //by default false
// on each second I'm checking promise has resolved or not.
var interval = setInterval(function() {
if (promiseResolved) {
console.log('Going to focus tab')
clearInterval(interval); //clearing interval
that.myWin.focus(); //focusing tab
}
}, 1000); // 1sec interval because of above assumption
//ajax call using $http
$http.get('').then(function() {
//set flag to true when promise resolved
promiseResolved = true;
console.log("I'm here");
});
};
I know I partially figured out what may be happening, but anyone can point out, if they find anything right/wrong in my answer. I'd appreciate that help. Thanks.
Demo Fiddle

Delaying window.open inside click event handler

For some days now I've been trying (without success) to open new window with delay without Chrome blocking it most of the time. Delay is crucial for my task, because some animation must take place before window is opened and I can not afford browsers to block new tabs from opening. Here is sample from my code:
element.on("click", function(e){
e.preventDefault();
var self = $(this),
url = self[0].href;
window.setTimeout(function(){
window.open(url);
}, 1000);
});
element is jQuery object (anchor element to be more precise). I have noticed that I have bigger success rate if I pass string directly like this
window.open("http://example.com");
I've tried this solution in Explorer(no problem), Chrome(problem), Firefox(no problem) and Opera(problem). I am loosing my mind, because I've tried everything I can remember. Synchronous ajax calls, artificially triggering click, creating fake anchor elements and artificially triggering click event. Nothing works fine.
Bonus question (in case someone knows how to solve problem): is there a way to call window.open anytime & anywhere from code?
This is working for me in Chrome http://jsbin.com/wuqopukayuwi/4/
var $element = $('#link');
$element.on('click', function () {
var url= $(this).attr('href');
window.setTimeout(function(){
var windowObjRef = window.open(url);
console.log(windowObjRef);
}, 2000);
});
Things to check:
Obviously, double check you've enabled popups for your domain in Chrome (it prompts you the first time it tries to pop up a new window
It's because Chrome expects to be able to access that window again programatically, so wants you to declare the response to the method as a variable. At least, that's how I got it working...
As long as you know how long the animation runs then you sleep for number of seconds
Add sleep(), msleep() and usleep() to Node.js, via a C++ binding.
This is mainly useful for debugging.
These calls will block execution of all JavaScript by halting Node.js' event loop!
Usage
`var sleep = require('sleep');
sleep.sleep(n): sleep for n seconds
sleep.msleep(n): sleep for n miliseconds
sleep.usleep(n): sleep for n microseconds (1 second is 1000000
microseconds)`

Javascript executing button click on page event

I'm new to javascript, and I'm trying to see if what I want to do is possible. I want to take a current webpage that I have open in my browser, and execute new javascript. There is a timer on this page, and when it increases to a particular time, I want it to execute a button click.
This would be the time that is changing and that I want to add into a if statement:
07:34:04
Will this changing time raise an event that would cause a javascript to run? I want something along the lines of:
if time = 7:35:00 then click button.
Thanks for your help!
I'll like to make a contribution..
I don't know much about the javascript time format, but I'll post back if I can look it up.
Any way you can use a function such as this:
var waiter;
function waitForTimer(extime, fn)
{
//Here, fn is the function to be executed..
//While extime is the time at which the function is to be executed..
waiter = setInterval(function(fn,extime){
//this function will check every one second..
if( extime == time )
{
fn();
clearInterval(waiter);
}
else
log("waiting for " + time);
}, 1000);
}
I hope this helps.

Annoying Popup - (or other more graceful solution)

Here's my "need" - I have a user opening a window with a document displayed, I need to log the amount of time the user has that window "in focus" or "opened"... IF the user views another window, I want to stop logging the time - and resume logging if they re-focus on that page... basically I want to "know" how long it took a user to read the page.
this is a review type scenario, where the users is a 'trusted' member who needs to log their time... I want to keep a 'running total' for reference only - so if the user says that spent 10 min, on the page, but my log shows the window was only open for 2min, I know I've got a problem...either with my code or my people.. ;)
My thought was to keep a js counter going when the page was in focus, pause on blur or on close, and Ajax the data back to my db... and add any subsequent time to that record if the user returns...
onUnload doesn't seem to work, at least when i try - plus it doesn't catch a closing of the browser... so I was thinking I could launch a NEW window, when the document window is closed (not to be annoying - but to make the logging call to the server, and then close itself).
Does anyone have a solution for this? I know this all smacks of 'poor' design, but if someone has a 'correct' way to handle this scenario - please tell me. (BTW- IE is a requirement- it's intranet based IE7 req.)
Thx
======== sample code below - that is 'not' working...kinda ============
When i say it's NOT working, this is what I mean... The "XMLHttpRequest" Is being made, i assume because the response is the message I'd expect - HOWEVER the log isn't changes (I know you'll say it's the php page, but if I call the url directly - it works fine... so it's no the logging page, IN ADDITION the 60 second setInterval() seems to fire randomly, because my response alert just pops up, sometime 10 in a row with no time between, certainly not at 'regular' 60 sec intervals... THOUGHTS?
<script type="text/javascript">
var closeMe = 0;
var logMe = 0;
//the window doesn't have focus, do nothing or something that let's them know we're not logging at the moment
function onBlur() {
//after 2 min of non focus, close it.
closeMe = setInterval('window.close()',120000); //after 2 min of non focus, close it.
};
//the window has focus... keep logging.
function onFocus(){
//stop the close counter - in the event to 'blurred' sometime
clearInterval ( closeMe );
//run the AJAX on a schedule - we're doing it every minute - bu tyou can do it as often as you like
logMe = setInterval('logTime()',60000);
};
//call a script that logs another minute...
function logTime() {
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "ajax-on-time-interval.php", false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
alert(serverResponse);
}
// check for Internet Explorer... IE uses 'onfocusin/out" - everything else uses "onfocus/blur"
if (/*#cc_on!#*/false) {
document.onfocusin = onFocus;
document.onfocusout = onBlur;
} else {
window.onfocus = onFocus;
window.onblur = onBlur;
}
</script>
I've have thought that a regular Ajax based "heartbeat" that updates the underlying database data every 'n' seconds (depending on the granularity you require, I'd have thought every minute would be sufficient) would be a neater solution than a pop-up and also avoid the fact that not all browsers handle onunload, etc. gracefully.
That said, I'm presuming that JavaScript will be enabled on these machines. (Seems fair based on your question.)
window.onfocus and onblur are documented in the MDC, but they're not standards. Evidently IE has document.onfocusin and .onfocusout :
if (/*#cc_on!#*/false) { // check for Internet Explorer
document.onfocusin = onFocus;
document.onfocusout = onBlur;
} else {
window.onfocus = onFocus;
window.onblur = onBlur;
}
I haven't tried it. I just read about it here.
http://www.thefutureoftheweb.com/blog/detect-browser-window-focus
One somewhat sloppy solution that partially resolves the issue with the browser closing/crashing is to have an ajax function that pings the server DB at a set interval while the document is in focus. This way, if the client crashes, you will be accurate within 30 seconds of how how long the document was open.

Categories

Resources