I have a timer on the home page. When user makes any action, such as mouse move, the timer will be reseted. When the timer count down to 05:00, system will pop-up a alert to reset timer by clicking "OK". If no action within 5 min and timer count down to 00:00, user forced to log out.
My problem is this timer only works within one page, if I have two pages opened, the timer only reset on focused page. I'll still be logged out due to the unfocused page.
Can anyone help me on this? Thanks so much!
<script type="text/javascript">
var flag = false;
startTimer();
function startTimer() {
var presentTime = $("#Status").text().toString();
var timeArray = presentTime.split(":");
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59) {
m=m-1;
if(m < 10) {
m = "0" + m;
}
}
if (m==05 && s==00) {
flag = true;
BootstrapDialog.alert("You have 5 minutes remaining in your session. Click \"OK\" to extend the session.", function() {
flag = false;
resetTimer();
});
}
if(!flag) {
//Reset timer upon user action
document.onload = resetTimer;
document.onmousemove = resetTimer;
document.onmousedown = resetTimer;
document.ontouchstart = resetTimer;
document.onclick = resetTimer;
document.onscroll = resetTimer;
document.onkeydown = resetTimer;
}
else {
document.onload = null;
document.onmousemove = null;
document.onmousedown = null;
document.ontouchstart = null;
document.onclick = null;
document.onscroll = null;
document.onkeydown = null;
}
if (m==0 && s==00) {
window.location.replace("/Logout");
};
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec};
if (sec < 0) {sec = "59"};
return sec;
}
function resetTimer() {
$("#Status").html("30:00");
}
</script>
<div> Your session has <h5 id="Status">30:00</h5> remaining. </div>
your problem is that you want to control two pages by 1 script,but variables in each page is independent.
if you solve this problem you could control your page.
you can get the variable m and s from cookie or localstorage. varibales in cookie and localstorage can be visit in different page if the these pages are in the same root.
try it,just replace the variables.get && set it from cookie or localstorage
Related
I created a stopwatch using JavaScript, and I'm trying to start/stop the timer by space key, but it doesn't stop but always became more faster.
'''
var timer_start = "S";
var time;
document.body.onkeyup = function (e) {
if (e.keyCode == 32) {
time = setInterval(timer, 10);
if (timer_start == "S") {
timer_start = "F";
} else if (timer_start == "F") {
clearInterval(time);
timer_start = "S";
}
}
};
,,,
Once the spacebar is pressed, you are starting the timer again regardless of the current value of timer_start. You need to move this to be inside the if statement. I'd also recommend using a Boolean instead of the string "S" and "F".
Here is my proposed rewrite of your code:
var timer_start = true;
var time;
document.body.onkeyup = function (e) {
if (e.keyCode == 32) {
if (timer_start) {
time = setInterval(timer, 10);
timer_start = false;
} else {
clearInterval(time);
timer_start = true;
}
}
};
You could also shorten it a bit by doing this if you wanted
var timer_start = true;
var time;
document.body.onkeyup = function (e) {
if (e.keyCode == 32) {
if (timer_start) {
time = setInterval(timer, 10);
} else {
clearInterval(time);
}
timer_start = !timer_start
}
};
You set the interval regardless of the timer_start state, so you keep piling up new intervals and remove only half of them. You should set the interval only in the timer_start == "S" branch.
I am trying to use the keypress event in my project to start a countdown timer but I keep getting a decrement for every keystroke.
I don't know what's wrong with my js code.
var timeleft = 60;
var timer = document.getElementById('timer');
var input = document.getElementById("input");
var timerId = setInterval(countdown);
input.addEventListener("keypress", countdown, 1000);
function countdown(event) {
if (event.key !==undefined){
if (timeleft == -1) {
clearTimeout(timerId);
}
else {
timer.innerHTML = timeleft;
timeleft--;
}
}
};
I want to build a timer controlled by one start button. when clicked, it will change innertext to "stop" and start the countdown, when clicked again, it will change to "continue" and pause the countdown. The problem is I don't know how to control the setinterval, because I declare it in dfferent if statment, I can't access the setinterval variable from other place.
Code:
const change = document.getElementById("change") -> countdown text part
const sb = document.getElementById("start") // button -> stop & pause
let stop = true;
let i; // setinterval variable
sb.addEventListener("click", () => {
let a = parseInt(change.innerText);
if(stop && a != 0) {
stop = false;
sb.innerText = "Stop";
i = setInterval(()=> {
a --;
change.innerText = a;
if(a == 0) {
stop = true;
alert("Time's Out!")
clearInterval(i);
sb.innerText = "Start";
}
}, 1000)
}
else if (!stop) {
stop = true;
sb.innerText = "continue";
// how to change this part to access setInterval variable i?
}
})
You should be able to call clearInterval within either section of your if-statement, since it is declared outside the scope of both. See here, a working example:
const s = document.querySelector('span');
const b = document.querySelector('button');
let interval = null;
b.onclick = () => {
// Start the interval
if (!interval) {
interval = setInterval(() => {
s.innerText = parseInt(s.innerText) - 1;
}, 1000);
b.innerText = "Pause";
} else {
clearInterval(interval);
interval = null;
b.innerText = "Resume";
}
}
<span id="countdown">100</span>
<button>Start</button>
I'm making a shot clock for my school's basketball team. A shot clock is a timer that counts down from 24 seconds. I have the skeleton for the timer right now, but I need to have particular key bindings. The key bindings should allow me to rest, pause, and play the timer.
var count=24;
var counter=setInterval(timer, 1000);
function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML=count + " secs";
}
I'm not sure what you meant by "rest" the timer, I interpret this as "pause", so:
Space = Pause / Play.
R = Reset.
var
count=24,
counter = setInterval(timer, 1000),
running = true;
function timer() {
count -= 1;
if (count <= 0) {
clearInterval(counter);
}
document.getElementById("timer").innerHTML = count + " secs";
}
window.addEventListener("keydown", function(e) {
switch(e.keyCode) {
case 32: // PLAY
running ? clearInterval(counter) : counter = setInterval(timer, 1000);
running = !running;
break;
case 82: // RESET
clearInterval(counter);
document.getElementById("timer").innerHTML = 24 + " secs";
count = 24;
running = false;
}
});
<div id="timer">24 secs</div>
I am not able to comment yet, but I recommend checking out this post Binding arrow keys in JS/jQuery
The linked post explains how to bind arrow keys using js/jquery. Using http://keycode.info/ you can find out the keycodes of your desired keys and replace the current values then continue to build your code from there.
Here is my code sample: http://codepen.io/anon/pen/vLvWJM
$(document).ready(function() {
var $timer = $('#timer');
var $timerStatus = $('#timerStatus');
var timerValue = 24;
var intervalId = null;
var timerStatus = 'stopped';
if(!$timer.length) {
throw 'This timer is missing a <div> element.';
}
$(document).keydown(function(k) {
if(k.which == 80) {
if(timerStatus === 'playing') {
clearInterval(intervalId);
timerStatus = 'stopped';
updateTimerStatus();
return;
}
intervalId = setInterval(function() {
playTimer();
timerStatus = 'playing';
updateTimerStatus();
}, 1000);
} else if(k.which == 82) {
clearInterval(intervalId);
resetTimer();
updateText();
timerStatus = 'stopped';
updateTimerStatus();
}
});
function playTimer() {
if(timerValue > 0) {
timerValue--;
updateText();
}
}
function resetTimer() {
timerValue = 24;
}
function updateText() {
$timer.html(timerValue);
}
function updateTimerStatus() {
$timerStatus.html(timerStatus);
}
});
<div id="timerStatus">stopped</div>
<div id="timer">24</div>
I have a Javascript block in which it creates a timer based on mouse movements. If you are not doing any activity the timer starts and when it reaches say 1 minute left time it displays an alert to the user and if the user does not respond it navigates to another page. The problem I am facing is that when I show an alert to the user the timer execution stops and it just waits for the user to press enter. What I need is that the timer should continue in the background whether the user clicks OK or not.
var mins, secs, TimerRunning, TimerID;
TimerRunning = false;
var activity;
document.documentElement.onmousemove = function () {
clearInterval(activity);
activity = Init();
// activity = setInterval(saySomething, 5000);
}
function Init() //call the Init function when u need to start the timer
{
mins = 2;
secs = 0;
StopTimer();
StartTimer();
}
function StopTimer() {
if (TimerRunning)
clearTimeout(TimerID);
TimerRunning = false;
}
function StartTimer() {
TimerRunning = true;
window.status = "if no activity is detected you will be logged out in " + Pad(mins) + ":" + Pad(secs);
TimerID = self.setTimeout("StartTimer()", 1000);
Check();
if (mins == 0 && secs == 0)
StopTimer();
if (secs == 0) {
mins--;
secs = 60;
}
secs--;
}
function Check() {
if (mins == 1 && secs == 0)
toggle();
alert("You have only 2 minutes remaining");
if (mins == 0 && secs == 0) {
window.location = "http://Test";
}
}
function Pad(number) //pads the mins/secs with a 0 if its less than 10
{
if (number < 10)
number = number;
return number;
}
Instead of using an alert, just use a modal dialog (basically a div that floats on top of everything else), or in the worst case a popup window.
I highly doubt this is feasible in javascript as it runs inside browser's ui thread...
But you can do what you want with jquery-ui (dialog widget) or similar javascript framework!