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!
Related
What's wrong with my code? I can't get the timer to stop at 0. It keeps going down to negative numbers. I have my clearInterval set, why isn't the timer stopping?
var seconds = 30;
$("#timer").on("click", run);
$("#timer").on("click", show);
var timer;
function run() {
clearInterval(timer);
timer = setInterval(decrement, 1000);
}
function decrement() {
seconds--;
$("#timer").html("<h2>" +"Time Remaining: " + seconds + "</h2>");
}
// Stop function
function stop() {
clearInterval(timer);
}
// When seconds hit zero
if (seconds === 0) {
stop();
alert("Time's Up!");
}
Your problem is that your if statement is run once, but it isn't ever checked again, and then never run again. If you move the if statement into your decrement function you should be good as gold.
The function might look something like,
function decrement() {
seconds--;
if (seconds === 0) {
stop();
alert("Time's Up!");
}
$("#timer").html("<h2>" +"Time Remaining: " + seconds + "</h2>");
}
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
I've created a countdown timer using javascript in asp.net. After completion of time, Button1 becomes disabled, but when I reload the page, the countdown timer is reset and Button1 is enabled.
I want to permanently disable Button1 when timer is equal to zero. My code is:
var tim;
var min = 01;
var sec = 00;
var f = new Date();
function f1() {
f2();
}
function f2() {
if (parseInt(sec) > 0) {
sec = parseInt(sec) - 1;
document.getElementById("showtime").innerHTML = ""+min+" Minutes ,"+sec+" Seconds";
tim = setTimeout("f2()", 1000);
}
else {
if (parseInt(sec) == 0) {
min = parseInt(min) - 1;
if (parseInt(min) == -1) {
clearTimeout(tim);
$("#Button1").prop('disabled', true);
}
else {
sec = 60;
document.getElementById("showtime").innerHTML = "" + min + " Minutes ," + sec + " Seconds";
tim = setTimeout("f2()", 1000);
}
}
}
}
<body onload="f1()">
<div><h3>Time will be finished after:</h3>
</div>
<div id="showtime"></div>
<div> <asp:Button ID="Button1" runat="server" Text="Submit"/></div>`
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
<script>
function f2() {
if (parseInt(sec) > 0) {
sec = parseInt(sec) - 1;
document.getElementById("showtime").innerHTML = ""+min+" Minutes ,"+sec+" Seconds";
tim = setTimeout("f2()", 1000);
}
else {
if (parseInt(sec) == 0) {
min = parseInt(min) - 1;
if (parseInt(min) == -1) {
clearTimeout(tim);
$("#Button1").prop('disabled', 'true');
storeValue('disabled', 'true');
}
else {
sec = 60;
document.getElementById("showtime").innerHTML = "" + min + " Minutes ," + sec + " Seconds";
tim = setTimeout("f2()", 1000);
}
}
}
}
function storeValue(key, value) {
if (localStorage) {
localStorage.setItem(key, value);
} else {
$.cookies.set(key, value);
}
}
function getStoredValue(key) {
if (localStorage) {
return localStorage.getItem(key);
} else {
return $.cookies.get(key);
}
}
function f1() {
f2();
var model =getStoredValue('disabled');
if(model == 'true')
{
$("#Button1").prop('disabled', 'true');
}
}
var tim;
var min = 01;
var sec = 00;
var f = new Date();
</script>
Use this code and make the thrid party localstorage to use in browser
When you reload the page, the state of the page is completely reset so it's as if a new visitor has found your page so you need to be able to store that state between visits.
One solution would be to use a cookie which you could set when the timer expires, and check for the presence of the cookie when the page loads. If it's there, disable the button straight away without a timer.
A more complicated solution would be to investigate saving session state on your server, but I've no idea what you have going on server-side so I can't give you much to go on there.
You could set a cookie when timer is off. And at every page load check for the cookie and disable the button if required. There is no other way.
FYI: you could use the same cookie to disable the button at server side itself.
Javascript
document.getElementById("myBtn").disabled = true;
or if u need it with a jquery- Click
$('.rbutton').on('click',function() {
$(this).prop("disabled",true);
});
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'm trying to create a shoppingcart with reservation time. The remaining time gets calculated by php. As the user enters the requested page, the time gets executed with the integer of seconds, that comes from php (session). If there are 3 minutes left, javascript starts a confirm-box and asks the user, if he wants to reset the timer to go on with his cart.
While the confirm-box is shown, the execution of the timer gets paused. How can I change my code, so that the timer runs without pausing it by the confirm-box?
//Starting the Counter in the document.ready-block
//remainingSeconds($_SESSION['timer']) is the time left in seconds (as int)
CountDownTimer('<?php echo remainingSeconds($_SESSION['timer']); ?>', 'reservedTime');
And here is the CountDownTimer function:
// These functions are located in an external .js-file
// Found it on StackOverflow and edited it for my needs
function CountDownTimer(dt, id)
{
if(id == "kill") {
clearInterval(timer);
} else {
var _second = 1,
_minute = _second * 60,
_hour = _minute * 60;
function showRemaining() {
var time = dt--,
minutes,
seconds;
if (dt == 180) {
var extend = confirm("Reset the timer?");
if (extend) {
resetCounter();
}
}
if (dt < 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = '00:00';
alert("No time left.");
//--redirect for readability removed--
return;
}
if(time > 59) {
minutes = Math.floor((time % _hour) / _minute);
seconds = Math.floor((time % _minute) / _second);
} else {
minutes = "0";
seconds = time;
}
if(minutes < 10) {minutes = "0"+minutes}
if(seconds < 10) {seconds = "0"+seconds}
document.getElementById(id).innerHTML = minutes + ":" + seconds;
}
timer = setInterval(showRemaining, 1000);
}
}
function resetCounter() {
request = $.ajax({url: "php/ajax.php?f=3"});
request.done(function (response, textStatus, jqXHR){
try {
var data = $.parseJSON(response);
CountDownTimer('0', 'kill'); // reset old counter
CountDownTimer(data.time, 'reservedTime'); // start new one
} catch(e) {
alert("ERROR ERMAGERD");
return false;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
alert("ERROR");
});
}
As the timer gets paused, it will create a time that differs from that in the session. So the cart might expire - but the user won't notice it and might lose his reserved items.
Edit: Or is there a better/secure method to integrate a shopping cart timer with output to the user, so that there won't be a time difference?