Timer display using Javascript/Jquery - javascript

I'm working on a thick client application which uses JavaScript and jQuery. My Session times out if it's left idle for 45 seconds or more (depending on different business/user).
Currently the timeout event is triggered by the vendor code to which I do not have access. I would like to display a timer on the screen if the session is found to be idle beyond a specific time threshold (for example: 25 seconds).
At the same time the timer should also match (marginal diff can be managed) with the third party timer (to which I do not have access).
Can someone suggest the best solution for this?

It's worth sharing any code you already have so that we can offer more precise advise for you.
However, to give you some pointers, take a look at the JavaScript window.setTimeout() method. It essentially triggers a callback after a set period of time. It's fairly safe to say that if your vendor is using JavaScript to keep track of time, then this is the same basic method they will be using too.
You can set and reset a timeout very easily so once set, you could listen for user interaction events (scrolling, clicking, etc) and use these to trigger a reset on the timeout (putting the 'count down' back to the start).
Do a bit of research, I'm sure you'll be able to develop a suitable solution!
With regards to interfacing with your vendor's timeout, without much more information none of us will be able to help. It doesn't sound like you have any control over this so it may not be possible (perhaps contact the vendor and ask?).
If you know what the timeout limits are for each use-case, you could ensure that your timeouts match theirs. However, this would be a little bit annoying given it's code-repetition and would also mean your application would 'break' if your vendor changes their timings.
TL/DR: Read into the JavaScript window.setTimeout() method if you want to write something that will do what you describe. However, the weak link will be that you don't have access to your vendor's timeout routines. With that in mind, my first step would be to contact the vendor and ask, they may have something in their API already available that you're unaware of!

Okay I don't quite get your logic, but a simple search on Google for jQuery plugin timer gives me:
http://www.tripwiremagazine.com/2013/04/jquery-countdown-scripts.html
A lot...
Hope one of them suits your needs.

Halo,
I finally managed to try a timer in my application (touch based). The following code works well for me.
var count = 50;
$(document).ready(function () {
var Timer = $.timer(function() {
$('#counter').html("Your Session will expire in " + --count + "seconds");
});
Timer.set({ time : 1000, autostart : true });
$(this).mousemove(function (e) {
idleTime = 0;
count = 50;
Timer.reset();
Timer.stop();
});
$(this).keypress(function (e) {
idleTime = 0;
count = 50;
Timer.stop();
Timer.reset();
});
var idleInterval = setInterval(function (){
idleTime = idleTime + 1;
if (idleTime > 10)
{
Timer.set({ time : 600, autostart : true });
$('#counter').css("display", "block");

Related

Javascript: How to speed up setTimeout function on website?

I am working on a website that asks me to complete a task, then once I complete that task it asks me to wait 1 hour before completing the next task.
What I am looking for here is to speed up the timer on this website instead of waiting for 1 hour.
How it works:
On Website I simply have to click on 'Roll' button then a timer start in descending order like (1:00)...(45:00)...(00:05) so on till it reach (00:00). Once it reach (00:00) it replace this timer to Roll button.
This timer only display Minutes and Second column.
It does not take computer time.
Changes I need:
Since it run in descending order or backward in seconds, I want to speedup this process so that instead of waiting for 1 hour I just have to wait for 20 or 30 minutes.
What I can't do:
Since this is a third party website so I cannot make changes in the website code I can only use browser console to run javascript code so I can override existing code on it.
Here is the Javascript for this timer:
<script>
$(function() {
$('#time_remaining').countdown({
until: +3600,
format: 'MS'
});
});
setTimeout(function() {
RefreshPageAfterFreePlayTimerEnds();
}, 3600 * 1000);
</script>
Looks like RefreshPageAfterFreePlayTimerEnds is global. So, you may try to override it like
var myTimeout = 3600; // 1 min
RefreshPageAfterFreePlayTimerEnds = function(speedUp) {
if(!speedUp) { // just to cancel "legal" call
return;
}
RefreshPageAfterFreePlayTimerEnds();
}
setTimeout(function(){ RefreshPageAfterFreePlayTimerEnds(true); }, myTimeout);
If you can't access to the website code, to change the code that doesn't allow you to reduce the time coding. You can change your IP address and use the website again.
If you have to sing in to use the website, forget, else you use another account and IP you will need to wait the time restricted to use again.

Javascript settimeout timer stopped while laptop lid is closed

When my system goes to hibernate mode, the javascript timer stop the countdown and when it comes back it continue with the countdown.
But my problem is that I'd like the countdown to continue when my system goes to hibernate mode. Is there any solution / workaround to achieve that?
This isn't really a javascript issue.
When you close the lid, your laptop is hibernating, meaning the CPU is switched off and cannot calculate things.
You have three options
1) Make the laptop stay on when closing the lid, or don't close the lid
2) Stop doing timer tasks client side, and instead simply start a timer on the server. Depending on what you are trying to achieve, this may or may not be relevant, but it is the only way to know the user will keep their lid open/browser open/machine on etc.
3) Re-work your code so instead of using a timer that says "wait ten seconds", you instead set it to use absolute times, something like the following (which is vague pseudo-code to demonstrate what I mean, not a working solution)
var targetTime;
var running = false;
startTimer(timeInSeconds)
{
targetTime = now() + timeInSeconds;
running = true;
}
while(running)
{
if(now() > targetTime)
{
doTimerThings();
running = false;
}
}
This will not get the timer precisely right, but will fire as soon as possible after the machine is started again. You can change your logic to suit how you wish to handle this (eg handling things differently if the timer is being fired late)
It won't help if you need to fire the timer at exactly the interval... but that simply isn't possible when the computer is off.

Loop function for specified time, followed by delay

I have a small piece of code that continuously clicks a button called "See Older Messages" every 500 ms, in order to load infinitely-scrolled content from a webpage. Reasons for doing this are personal, but needless to say, I'm trying to automate something which would take me weeks of non-stop scrolling to do otherwise.
The problem is that the 500 ms delay gradually begins to drop as the script runs over time. After so many hours, it can take 5 seconds or more. I'm assuming this problem is caused by Facebook throttling my requests after so long, so to prevent this, I want to make the script run for an amount of time - say 2 minutes - followed by a delay of maybe 20 secs before it runs again for 2 mins, and so on. How would I go about doing this? I've racked my brains, but my limited knowledge of JavaScript hasn't come up with anything meaningful.
Below is the current code in its entirety.
setInterval(function () {
document.getElementById('see_older').getElementsByClassName('content')[0].click();
}, 500);
Thanks a lot in advance.
Keep track of when the script running started
While it's been less than 2 mins, keep clicking every 500ms.
After running for ~2 mins, stop and queue next run in 20s.
Go to step 2.
-
var lastChange;
function doClick() {
if (new Date() - lastChange < 120000 /* 2 mins */) {
document.getElementById('see_older').getElementsByClassName('content')[0].click();
setTimeout(doClick, 500);
} else setTimeout(runScript, 20000 /* 20s */);
}
(function runScript() {
lastChange = new Date();
doClick();
})();
-
I recommend using setTimeout over setInterval since, if the browser takes a while to execute, loses focus and stops executing JS, gets paged out, etc., then you will still get the time spacing between events that you want. See https://stackoverflow.com/a/731625/1059070.
Toggle whether or not your function does anything by setting another timer.
/* When true do load else don't. */
window.doLoad = true
setInterval(function () {
if window.doLoad {
document.getElementById('see_older').getElementsByClassName('content')[0].click();
}
}, 500);
/* This will toggle doLoad every two minutes. */
setInterval(function () {
if (window.onLoad == true) {
window.doLoad = false;
} else { window.doLoad = true; }
}, 120000); // two minutes of milliseconds
In your case though you might be better off using the Facebook Graph API.
Graph API documentation from Facebook
Here's an existing question with the API using Python to do basically the same thing you want to do.
JS question, also similar

Cancel Javascript timeout

I have a long process hosted on a Web Server. The thing is triggered from a Web Page, at the click of a button by a user. Some Javascript polls regularly via Ajax to check if the operation has completed server side. To do this, I use setInterval, and later on clearInterval to stop polling.
If this takes too long (e.g. server has crashed), I'd like the client to be informed by some sort of timeout. I've done some research and found about setTimeout. Problem is, if the operation finishes successfully before the timeout, I'd like to cancel this one.
How to do this ?
Would you suggest a different approach ?
PS : I'm targetting IE7/IE8 in particular, but always open to some JQuery
As long as you store your interval's id in a variable, you can use it to clear the interval at any time.
var interval = window.setInterval(yourFunction, 10000);
...elsewhere...
window.clearTimeout(interval);
For more information see the Mozilla Documentation's setInterval example.
Put together a quick JS Fiddle containing a modified version of Mozilla's Example.
To clear a setTimeout, use clearTimeout.
You want two timers (as you said)
repeating interval to do the next poll and
one-time expiration to give up if the server never responds
If the polling is successful you want to clear both the polling interval and cancel the failure timer. If the expiration timer fires you want to clear the polling interval
var checkCount = 0;
function checkComplete() {
console.log("test " + checkCount);
if (checkCount++ > 10) {
console.log("clearing timeout");
window.clearInterval(pollInterval);
window.clearTimeout(expireTimer);
}
}
function cancelPolling(timer) {
console.log("clearing poll interval");
window.clearInterval(pollInterval);
}
var pollInterval = window.setInterval(checkComplete, 500);
var expireTimer = window.setTimeout(cancelPolling, 10000);
You can fiddle with the checkCount constant "10" - keep it low to simulate polling success, raise it higher for the timeout to occur before the checkCount is reached, simulating polling failure.

How to know if a page is currently being read by the user with Javascript?

I'm making a webpage with dynamic content that enters the view with AJAX polling. The page JS occasionally downloads updated information and renders it on the page while the user is reading other information. This sort of thing is costly to bandwidth and processing time. I would like to have the polling pause when the page is not being viewed.
I've noticed most of the webpages I have open spend the majority of their time minimized or in a nonviewed tab. I'd like to be able to pause the scripts until the page is actually being viewed.
I have no idea how to do it, and it seems to be trying to break out of the sandbox of the html DOM and reach into the user's system. It may be impossible, if the JS engine has no knowledge of its rendering environment. I've never even seen a different site do this (not that the user is intended to see it...)
So it makes for an interesting question for discussion, I think. How would you write a web app that is CPU heavy to pause when not being used? Giving the user a pause button is not reliable, I'd like it to be automatic.
Your best solution would be something like this:
var inactiveTimer;
var active = true;
function setTimer(){
inactiveTimer = setTimeOut("stopAjaxUpdateFunction()", 120000); //120 seconds
}
setTimer();
document.onmouseover = function() { clearTimeout ( inactiveTimer );
setTimer();
resumeAjaxUpdate();
}; //clear the timer and reset it.
function stopAjaxUpdateFunction(){
//Turn off AJAX update
active = false;
}
function resumeAjaxUpdate(){
if(active == false){
//Turn on AJAX update
active = true;
}else{
//do nothing since we are still active and the AJAX update is still on.
}
}
The stopAjaxUpdateFunction should stop the AJAX update progress.
How about setting an "inactivity timeout" which gets reset every time a mouse or keyboard event is received in the DOM? I believe this is how most IM programs decide that you're "away" (though they do it by hooking the input messages at the system-wide level)
I've looked at that problem before for a research project. At the time (2-3 years ago) I did not find a way to get information from the browser about whether or not you are minimized :(
First check when the window loses and gains focus.
window.onblur = function () { /* stop */ };
window.onfocus = function () { /* start */ };
Also, for various reasons, the user may stop reading the page without causing it to lose focus (e.g. he gets up and walks away from the computer). In that case, you have to assume after a period of inactivity (no mouse or keyboard events) that the users' attention has left the page. The code to do that is described in another answer.
I know you've already accepted an answer but I'd personally use a combination of several of the answers mentioned here for various reasons, including:
Using mouse events only alienates users proficient at keyboard based browsing.
Using blur/focus events don't allow for users who go make a cup of tea ;-)
I'd most likely use something like the following as a guideline:
var idleTimer, userIsIdle, pollingTimer;
document.onkeydown = document.onmousemove = resetTimer;
window.onload = function () {
pollingTimer = window.setTimeout(runPollingFunction, 30000);
resetTimer();
/* IE's onblur/onfocus is buggy */
if (window.navigator.appName == "Microsoft Internet Explorer")
document.onfocusin = resetTimer,
document.onfocusout = setIdle;
else
window.onfocus = resetTimer,
window.onblur = setIdle;
}
function resetTimer() {
if (userIsIdle)
setBack();
window.clearTimeout(idleTimer);
idleTimer = window.setTimeout(setIdle, 120000); // 2 minutes of no activity
}
function setIdle() {
userIsIdle = true;
window.clearTimeout(pollingTimer); // Clear the timer that initiates polling
window.clearTimeout(setIdle);
}
function setBack() {
userIsIdle = false;
runPollingFunction(); // call the polling function to instantly update page
pollingTimer = window.setTimeout(runPollingFunction, 300000);
}
You can listen for mousemove and keypress events. If one of those has been fired in the past X seconds, then continue with your updating. Otherwise, don't update.
It's not perfect, but I think it's the best you can do with pure JS.
If you want to venture into the world of Flash, Silverlight, or Java, you may be able to get more information from the browser.

Categories

Resources