I am building a site where task is assigned to each user and he/she needs to complete the task within a fixed duration of time.
For this is need to track Time taken on each task. I also need to track if the user is sitting idle on the site.
Right now i can do this using this code :
HTML
<a class="btn btn-success btn-lg" id="startTracking" role="button">Start Tracking</a>
<a class="btn btn-danger btn-lg" id="endTracking" role="button">Stop Tracking</a>
<h2 id="testingSince"></h2>
JAVASCRIPT
<script type="text/JavaScript">
var totalSeconds = 0;
var idleSeconds = 0;
$(document).ready(function () {
$('body').on('click','#startTracking',function(){
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 1000); // 1 second
});
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleSeconds = 0;
});
$(this).keypress(function (e) {
idleSeconds = 0;
});
});
function timerIncrement() {
totalSeconds += 1;
idleSeconds += 1 ;
if (idleSeconds > 600) { // 20 minutes
alert('You have been sitting Idle for 10 Minutes');
}
$('#testingSince').text(timeStringfromSeconds(totalSeconds));
}
function timeStringfromSeconds(totalSeconds){
var hours = Math.floor(totalSeconds / 36e2),
mins = Math.floor((totalSeconds % 36e2) / 60),
secs = Math.floor((totalSeconds % 60));
return ("0" + hours).slice(-2)+':'+("0" + mins).slice(-2)+':'+("0" + secs).slice(-2);
}
</script>
So this code works great and the user can see the time spent since he clicked the button. It also tracks user idle time and gives an alert after 10 minutes.
However the only Problem here is that when the page reloads the counter starts from 0. i.e the 2 lines :
var totalSeconds = 0;
var idleSeconds = 0;
I just want the timer counter not to restart and continue from its previous value.
One way of doing this is using Cookies. So i have to update them every second but i am not sure if this is a good Idea.
Please let me know if there is any other way or i need to use browser cookies ?
Many users will not permit cookies on their computers. You should never rely only on cookies. Maybe you should make some script that you can ajax call every second or two or five and store elapsed time in session.
Related
I have very little experience in coding in general, however, I still need a timer that comes on a pop-up that goes from 20 or 30 minutes to 0, and it should display the time remaining (like MM:SS). Then, when the timer hits 0, a new pop-up should appear that displays some plain text. Is this even possible?
This could do the work
let time = 5;
let element = document.getElementById('countdown');
function lower() {
if(time >= 0) {
element.innerHTML = time--;
}
else {
console.log('popup')
//open popup here
}
}
setInterval(lower, 1000);
I did not do the time format tho. Only shows in seconds now
I have a script that AJAXes a request every 10 seconds (but technically 11), for the user. I have a simple countdown made from 10 to 0 and then again and again.
This countit function is called after each AJAX request to restart
Here is my code:
function countit() {
var count = 10;
loading = setInterval(function() {
$(box).val("Will automatically check in " + count + "second(s), please DO NOT refresh the page yourself.");
count--;
if (count <= 0) {
clearInterval(loading);
}
}, 1000);
}
The code works fine except, if you leave the page and come back, the countdown proceeds into negative and does not stop. Here is the image:
I cant be sure if this is a problem with the code or JS but the counter doesnt go below 0 when the user stays on the page.
As Ibrahim & Chris have said:
Add a var infront of the Interval as without it, the variable is global.
function countit() {
var count = 10;
var loading = setInterval(function() {
$(box).val("Will automatically check in " + count + "second(s), please DO NOT refresh the page yourself.");
count--;
if (count <= 0) {
clearInterval(loading);
}
}, 1000);
}
The clearInterval function only stops the timer in my code, but not the actual time. After I click the stop button, the timer stops, but it seems like it is still running in the background. When I re-click the start button again, it does not resume from where it stop, but show me the actual time that has been running in the background. Please see the action in the code.
How can I really stop the timer and resume it after I click on the stop button by clicking on the start button again?
var timeBegan = new Date();
function start(){
started = window.setInterval(clockRunning, 10);
}
function stop(){
window.clearInterval(started);
}
function clockRunning(){
currentTime = new Date()
, timeElapsed = new Date(currentTime - timeBegan)
, hour = timeElapsed.getUTCHours()
, min = timeElapsed.getUTCMinutes()
, sec = timeElapsed.getUTCSeconds()
, ms = timeElapsed.getUTCMilliseconds();
document.getElementById("display-area").innerHTML =
(hour > 9 ? hour : "0" + hour) + ":" +
(min > 9 ? min : "0" + min) + ":" +
(sec > 9 ? sec : "0" + sec) + "." +
(ms > 99 ? ms : ms > 9 ? "0" + ms : "00" + ms);
};
function reset(){
window.clearInterval(started);
running = 0;
hour = min = sec = ms = 0;
document.getElementById("display-area").innerHTML = "00:00:00.000";
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Stopwatch</title>
<script src="stopwatch.js"></script>
<style>
#display-area { font-size: 20pt; }
</style>
</head>
<body>
<div>
<output id="display-area">00:00:00.000</output>
</div>
<div>
<button id="start-button" onClick="start()">Start</button>
<button id="stop-button" onclick="stop()">Stop</button>
<button id="reset-button" onclick="reset()">Reset</button>
</div>
</body>
</html>
This is because you never reset timeBegan. You are continuing to use the same value for the start time.
You need to set this value to the current time within start(), otherwise you are just using the time the page loaded as your reference time instead of the time that start() was last invoked.
var timeBegan;
function start() {
timeBegan = new Date();
started = window.setInterval(clockRunning, 10);
}
Alternatively, you can do this within reset(), and then a stop click followed by a start click will act more like a lap timer; you can freeze the time, but in the background it would keep counting until you click the reset button.
If you want the stop button to pause the timer, then at the moment you click stop you need to record the current duration somewhere. Then in your clockRunning() function you would add this duration to whatever your time subtraction calculation yields. (And, of course, reset() should clear out this stored duration.)
Instead of your current implementation of timeElapsed, what you would want is to make timeElapsed a sum counter where for every call of clockRunning, you would add the time difference from the last clockRunning call to timeElapsed.
start should start/resume clockRunning function calls
clockRunning should add to timeElapsed the time difference from the last clockRunning call
stop should stop clockRunning function calls, and set the clockRunning call time to something like null or -1.
In start, if the last time clockRunning is called is null or -1 (basically, if stop was called), set the last time clockRunning is called to now.
I have a little problem regarding browser window closing,
Basically, I have a page which I want to close after 15 minutes of inactivity. I alraeady managed to make a timer that will alert the window after inactivity for 10 minutes.
What I need is that on timer finish, a popup/alert with a visible countdown comes up and from here the user can either continue with his session or end it. If the user does not click on continue or ignore the popup for 5 more minutes, both the popup and parent window will close. Else if the user presses continue the popup will close and the main page is refreshed (and thus starting the timer again) Any suggestions? Here is my code:
var idleTime = 0;
var activeTime = 0;
var warningFlag = 0;
var loginTime = new Date();
var logoutTime = loginTime;
setInterval(function checkIdle() {
idleTime += 1;
activeTime += 1;
if(idleTime > 10) {
alert("You've been inactive for 10 \n minutes, are you still there ?\nYou logged in at " + loginTime);
warningFlag=1;
}
if((idleTime > 15) && (warningFlag==1)) {
alert("You've been logged out due to inactivity for 15 \n minutes? \nYou logged out at " + logoutTime);
window.close();
}
window.onload = resetTimer;
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;
},1000);
function resetTimer() {
idleTime = 0;
}
Instead of alert window use a div for that visibility hidden/visible is toggled. That div should contain another container, div or span, for displaying the countdown time.
You can use modal windows, they behave like alerts by displaying a div and blacking out the rest of the page.
You can see some good examples here:
http://www.scriptiny.com/2011/03/javascript-modal-windows/
Hope this helps.
After some specified inactivity time (IDLE Time say for 10 mins) the application should give a pop up box with a timer (should display like 60 59 58 ....1), that box should close within 60 secs with cancel option selected and that browser should close if user doesn't select any option. If the user selects the cancel option within 60 secs also it should be closed.
To show a popup box I am using setTimeout("pop()",600000); but how to include a timer in that at least that box should close within 60 sec if user doesn't select any option. Is there a solution for this?
You may try putting below code in your popup window.
<script>
function mytimer()
{
setTimeout(function closewin(){window.close;}, 600000);
}
</script>
<body onload="mytimer();">
You can use setTimeout() or setInterval() again. In your pop() function, start another function with a timeout of 1 second (1000ms) and on each call decrease a counter and update the label. When the counter reaches 0, check that the box is still on the screen and if so call window.close() (not all browsers will actually respond to a closing attempt though).
Example:
function pop() {
var counter = 60;
var box = document.createElement('div');
var label = document.createElement('span');
label.innerText = counter;
box.appendChild(label);
// Position box and label as you wish.
function tick() {
counter--;
if (counter == 0) {
window.close();
} else {
label.innerText = counter;
setTimeout(tick, 1000);
}
}
setTimeout(tick, 1000);
}