Delay in timer when tab is inactive or browser minimised - javascript

I have the following code to show a timer for an online quiz application.On completion , I need to redirect to another page via ajax.
The code works for me,but I found that the timer delays when we shift tabs or minimise the browser.
var mins = 5;
var secs = 0; // Seconds (In addition to min) test time
var timerDisplay = $(document).find('#timerspan');
//Globals:
var timeExpired = false;
// Test time in seconds
var totalTime = secs + (mins * 60);
var countDown = function (callback) {
var interval;
interval = setInterval(function () {
if (secs === 0) {
if (mins === 0) {
timerDisplay.text('0:00');
clearInterval(interval);
callback();
return;
} else {
mins--;
secs = 60;
}
}
var minute_text;
if (mins > 0) {
minute_text = mins;
} else {
minute_text = '0';
}
var second_text = secs < 10 ? ('0' + secs) : secs;
timerDisplay.text(minute_text + ':' + second_text);
secs--;
}, 1000, timeUp);
};
// When time elapses: submit form
var timeUp = function () {
alert("Time's Up!");
timeExpired = true;
var completed=1;
$.ajax({
type:"POST",
url:"success.php",
data:{'userID':<?php echo $_SESSION['userID'];?>},
success: function (hasil) {
$('.response_div').html(hasil);
}
});
};
// Start the clock
countDown(timeUp);

Related

Javascript, Make time in stopwatch editable

I am attempting to make my javascript stopwatch run inside some sort of input box, this way if I wanted to change the current calculated time I could just edit the hour, minute, or second. I tried making the time wrapped inside of html tags but the time would not send from the script into the boxes. Any better ideas of how to make this work???
Javascript
function _timer(callback)
{
var time = 0; // The default time of the timer
var status = 0; // Status: timer is running or stoped
var timer_id; // This is used by setInterval function
// this will start the timer
this.start = function(interval)
{
interval = (typeof(interval) !== 'undefined') ? interval : 1000;
if(status == 0)
{
status = 1;
timer_id = setInterval(function()
{
switch(1)
{
case 1:
if(time < 86400)
{
time++;
generateTime();
if(typeof(callback) === 'function') callback(time);
}
break;
}
}, interval);
}
}
// this will stop or pause the timer ex. timer.stop()
this.stop = function()
{
if(status == 1)
{
status = 0;
clearInterval(timer_id);
}
}
// Reset the timer to zero or reset it to your own custom time
this.reset = function(sec)
{
sec = (typeof(sec) !== 'undefined') ? sec : 0;
time = sec;
generateTime(time);
}
// This methode return the current value of the timer and sends it to the database
this.getTime = function()
{
return time;
}
// This methode return the status of the timer
this.getStatus
{
return status;
}
// This methode will render the time variable to hour:minute:second format
function generateTime()
{
var second = time % 60;
var minute = Math.floor(time / 60) % 60;
var hour = Math.floor(time / 3600) % 60;
second = (second < 10) ? '0'+second : second;
minute = (minute < 10) ? '0'+minute : minute;
hour = (hour < 10) ? '0'+hour : hour;
$('div.timer span.second').html(second);
$('div.timer span.minute').html(minute);
$('div.timer span.hour').html(hour);
}
}
var timer;
$(document).ready(function(e)
{
timer = new _timer
(
function(time)
{
if(time == 0)
{
timer.stop();
}
}
);
timer.reset(0);
});
HTML
<div class="timer">
<span class="hour"></span>:<span class="minute"></span>:<span class="second"></span>
</div>
<div>
<button onClick="timer.start(1000)">Start</button>
<button onClick="timer.stop()">Stop</button>
<button onClick="timer.reset(0)">Reset</button>
</div>
Here's the final working solution.
Javascript
function _timer(callback, interval)
{
var time = time || 0; // The default time of the timer
var status = 0; // Status: timer is running or stoped
var timer_id; // This is used by setInterval function
var interval = interval || 1000;
// this will start the timer
this.start = function()
{
verifyTime();
if(status == 0)
{
status = 1;
timer_id = setInterval(function()
{
switch(1)
{
case 1:
if(time < 86400)
{
time++;
generateTime();
if(typeof(callback) === 'function') callback(time);
}
break;
}
}, interval);
}
}
// this will stop or pause the timer ex. timer.stop()
this.stop = function()
{
if(status == 1)
{
status = 0;
clearInterval(timer_id);
}
}
// Reset the timer to zero or reset it to your own custom time
this.reset = function(sec)
{
time = 0
generateTime()
}
// This methode return the current value of the timer and sends it to the database
this.getTime = function()
{
return time;
}
// This methode return the status of the timer
this.getStatus
{
return status;
}
// This methode will render the time variable to hour:minute:second format
function generateTime()
{
console.log(time);
second = time % 60;
minute = Math.floor(time / 60) % 60;
hour = Math.floor(time / 3600) % 60;
second = (second < 10) ? '0'+second : second;
minute = (minute < 10) ? '0'+minute : minute;
hour = (hour < 10) ? '0'+hour : hour;
$('div.timer input.second').val(second);
$('div.timer input.minute').val(minute);
$('div.timer input.hour').val(hour);
}
function verifyTime()
{
var verifySec = Number($('div.timer input.second').val());
second = time % 60;
verifySec === second ? second = second : time += verifySec - second % 60;
var verifyMin = Number($('div.timer input.minute').val());
minute = (verifyMin - Math.floor(time / 60)) * 60;
verifyMin === minute ? minute = minute : time += (verifyMin - Math.floor(time / 60)) * 60;
var verifyHour = Number($('div.timer input.hour').val());
hour = ((verifyHour - Math.floor(time / 3600)) * 60) * 60;
verifyHour === hour ? hour = hour : time += ((verifyHour - Math.floor(time / 3600)) * 60) * 60;
}
}
var timer;
$(document).ready(function(e)
{
timer = new _timer
(
function(time)
{
if(time == 0)
{
timer.stop()
}
},
1000
);
$('#start').click(timer.start)
$('#stop').click(timer.stop)
$('#reset').click(timer.reset)
$('.hour').focus(timer.stop)
$('.hour').focusout(timer.start)
$('.minute').focus(timer.stop)
$('.minute').focusout(timer.start)
$('.second').focus(timer.stop)
$('.second').focusout(timer.start)
});
HTML
<div class="timer">
<input type='text' class="hour" />:<input type='text' class="minute" />:<input type='text' class="second" />
</div>
<div>
<button id='start'>Start</button>
<button id='stop'>Stop</button>
<button id='reset'>Reset</button>
</div>

how could I implement break time countdown using same function pomodoro clock

I'm working on a pomodoro clock and functionality is almost done, except I'm having difficulty implementing breakTime countdown without rewriting countDown() function just for breakTime. I got the impression I can reuse countDown function for break time. I just don't know how. If someone could give me some clues / code? thanks Project https://codepen.io/zentech/pen/vJGdjN
Javascript
$(document).ready(function() {
//variables
var workTime = $(".work").text(); //working time
var breakTime = $(".break").text(); //break time
var seconds = 00;
var minutes = workTime; //setting clock = to workTime
var clockDisplay = document.getElementById("display");
var counterId = 0;
var state = "on";
//start / stop listener functionality
$("#start").click(function() {
var value = $(".button").text();
console.log(value);
if(value == "Start") {
state = "on";
console.log("started!");
//starting counter
counterId = setInterval(countDown, 1000);
$("#session").text("Working");
$(".button").text("Stop");
}
else {
console.log("stopped");
state = "off";
minutes = workTime;
seconds = 0;
//clear counter
clearInterval(counterId);
clockDisplay.innerHTML = workTime +":00";
$(".button").text("Start");
}
});
//add work time
$('.plusWork').click(function() {
workTime++;
minutes = workTime;
$('.work').text(workTime);
clockDisplay.innerHTML = workTime +":00";
console.log(workTime);
});
//substract work time
$('.minWork').click(function() {
workTime--;
minutes = workTime;
$('.work').text(workTime);
clockDisplay.innerHTML = workTime +":00";
console.log(workTime);
});
//add break time
$('.plusBreak').click(function() {
breakTime++;
minutes = breakTime;
$('.break').text(breakTime);
console.log(breakTime);
});
//substract break time
$('.minBreak').click(function() {
breakTime--;
minutes = breakTime;
$('.break').text(breakTime);
console.log(breakTime);
});
//work countdown timer function
function countDown() {
//if workTime = 0 reset counter and stop
if(minutes == 0 && seconds == 0 && state == "on") {
clearTimeout(counterId);
//if work countdown reach 0, start break
minutes = breakTime;
seconds = 00;
setInterval(countDown, 1000);
return;
}
else if(minutes == 0 && seconds > 0) {
seconds--;
if(seconds < 10) seconds = "0"+seconds;
clockDisplay.innerHTML = minutes + ":" + seconds;
console.log(minutes +":"+seconds +" 2");
}
//when seconds < 0 substract a minute
else if(minutes > 0 && seconds < 0) {
minutes--;
seconds = 59;
clockDisplay.innerHTML = minutes + ":" + seconds;
console.log(minutes +":"+seconds +" 3");
}
else {
//if second single digit add 0
if (seconds < 10) seconds = "0"+seconds;
clockDisplay.innerHTML = minutes +":"+ seconds;
seconds--;
console.log(minutes +":"+seconds +" 4");
}
}
});

Javascript Pomodoro Clock - clearInterval not working when timer is 0

I am making a simple podomoro clock, and everything seems to work fine except when timer reaches 0 its doesn't entirely stop. Minutes seem to stop but seconds keep decrementing. I think there might be something wrong with my startTimer function but I've tried tinkering with it for hours to no result.
JS:
$(document).ready(function() {
var pomoTime = $('#pomodoroNum');
var breakTime = $('#breakNum');
var status = $('#timerStatus');
var timerDisplay = $('#timer');
var startButton = $('#startBtn');
var stopButton = $('#stopBtn');
var state = 1; // 1=stopped 2=running
var countDown; // intervalID;
var minutes = 0;
var seconds = 60;
startButton.click(function() {
if (state == 1) { // if timer is not running then start timer
startTimer(minutes, seconds);
$('#breakMinus').off("click");
$('#breakPlus').off("click");
$('#workMinus').off("click");
$('#workPlus').off("click"); // disable +- controls when timer starts
};
});
updateDisplay(); // initially controls are enabled at the start
stopButton.on("click", function() {
if (state == 2) {
pauseTimer();
state = 1;
updateDisplay(); // renable +- controls when timer stops
}
});
function startTimer(m, s) {
state = 2;
var startMinutes = m;
var startSeconds = s;
countDown = setInterval(function() {
startSeconds--;
startMinutes = ("0" + startMinutes).slice(-2); // double digits conversion if <10
startSeconds = ("0" + startSeconds).slice(-2);
minutes = ("0" + startMinutes).slice(-2); // update minutes and seconds so when timer is stopped, it can resume from where it left off when startButton is pressed.
seconds = ("0" + startSeconds).slice(-2);
timerDisplay.html(startMinutes + ":" + startSeconds);
if (startSeconds == 0 && startMinutes > 0) {
startMinutes-- // decerement minutes when seconds 0...
startSeconds = 60; // ..and reset seconds to 60
}
}, 1000);
if (startMinutes == 0 && startSeconds == 0) {
clearInterval(countDown);// <-- not clearing here
}
};
function pauseTimer() {
clearInterval(countDown);
};
function updateDisplay() {
// break +-
$('#breakMinus').on("click", function() {
status.html("Break");
if (breakTime.text() > 1) {
breakTime.text(+breakTime.text() - 1);
};
timerDisplay.text(breakTime.text());
});
$('#breakPlus').on("click", function() {
status.html("Break");
breakTime.text(+breakTime.text() + 1); // parseInt to covert string into number so it doesn't concatanate.
timerDisplay.text(breakTime.text());
});
// work +-
$('#workMinus').on("click", function() {
status.html("Work");
if (pomoTime.text() > 1) {
minutes = pomoTime.text() - 2;
}
seconds = 60;
if (pomoTime.text() > 1) {
pomoTime.text(+pomoTime.text() - 1);
};
timerDisplay.text(pomoTime.text());
});
$('#workPlus').on("click", function() {
minutes = pomoTime.text();
seconds = 60;
status.html("Work");
pomoTime.text(+pomoTime.text() + 1); // parseInt to covert string into number to prevent concatanation.
timerDisplay.html(pomoTime.html());
});
};
});
example: http://codepen.io/aliz16/pen/OXMwRJ
Your check for the stop condition is outside of your interval function. That's why it's never stopping. Move the condition inside the function and use <= to be extra safe:
if (startSeconds <= 0 && startMinutes > 0) {
startMinutes -= 1; // decerement minutes when seconds 0...
startSeconds += 60; // ..and reset seconds to 60
}
if (startMinutes <= 0 && startSeconds <= 0) {
clearInterval(countDown);
}
}, 1000);

stop timer when switch between tabs in browser

Here is my script written
I want to stop timer when user switch to different tabs and resume back when visit the site. can anyone help me to solve this task.
$(document).ready(function() {
window.setInterval(function() {
var timeLeft = $("#timeLeft").html();
if(eval(timeLeft) == 0){
window.location= ($("#url_online").html());
}else{
$("#timeLeft").html(eval(timeLeft)- eval(1));
}
}, 1000);
});
var time=$("#times").html();
var tt=time.split(":");
var seconds =tt[0]*60+tt[1]*1;
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Buzz Buzz";
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
<p id="times"> 2:50</p>
Redirect You In <span id="timeLeft">40</span> secs..
You can use $(window).focus() and $(window).blur() event.
Example:
https://jsfiddle.net/72cLu8c0/
I done the task with following code and working fine in my php project.
<script src="http://newnuk.com/newnuk/newnuk/themes/newnuk/assets/js/jquery.min.js"></script>
<script type="text/javascript">
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var a=duration;
setInterval(function () {
if (window.isActive) {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
//interval check and calling function
a=parseInt(a, 10)-1;
if(a==0) {
showpanel();
$('#timer1').hide();
return false;
}
display.text(minutes + ":" + seconds);
if (--timer < 0) {
alert('hi');
timer = duration;
}
}
}, 1000);
}
jQuery(function ($) {
var fiveMinutes =<?php echo $time ;?>,
display = $('#time');
startTimer(fiveMinutes, display);
// use setTimeout() to execute
//setTimeout(showpanel, 181000)
});
$(function() {
window.isActive = true;
$(window).focus(function() { this.isActive = true; });
$(window).blur(function() { this.isActive = false; });
showIsActive();
});
function showIsActive()
{
console.log(window.isActive)
window.setTimeout("showIsActive()", 2000);
}
function showpanel() {
var dataString = 'adv='+'MTE=';
$.ajax({
type: "POST",
url: baseurl + "advs/viewed_adv/true",
dataType: "json",
data: dataString,
cache: false,
success: function(json) {
if(json.viewed==true)
{
$('#viewed_sucess').show();
$('#timer1').hide();
}
}
});
}
</script>
<div style="font-size:40px; font-weight:bold;" id="timer1"><span id="time" style="color:red;"></span></div>
<?php
$timer_var = 65;
?>

Game Timer Javascript

I'm creating a countdown timer. If seconds is equal to zero I have set 2 secs to var seconds. Please help. I need to stop the program from looping after getting the 2 seconds
var isWaiting = false;
var isRunning = false;
var seconds = 10;
function GameTimer(){
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if(remainingSeconds < 10){
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('waiting_time').innerHTML = minutes + ":" + remainingSeconds;
if(seconds == 0){
isRunning = true;
seconds += 2; //I need to stop the program from looping after getting the 2 seconds
}else{
isWaiting = true;
seconds--;
}
}
var countdownTimer = setInterval(GameTimer(),1000);
Here is your fixed code:
var isWaiting = false;
var isRunning = false;
var seconds = 10;
var countdownTimer;
var finalCountdown = false;
function GameTimer() {
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('waiting_time').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
isRunning = true;
seconds += 2;
if (finalCountdown) {
clearInterval(countdownTimer); // Clear the interval to stop the loop
} else {
finalCountdown = true; // This will allow the 2 additional seconds only once.
}
} else {
isWaiting = true;
seconds--;
}
}
countdownTimer = setInterval(GameTimer, 1000); // Pass function reference, don't invoke it.
WORKING DEMO: http://jsfiddle.net/nEjL4/1/
since i couldn't understand the code that's up in the question i wrote down my own timer. So take a look if it works out for you.
http://jsfiddle.net/9sEGz/
var m=getId('m'), s=getId('s'), btn=getId('btn'), status=getId('status'), inc =getId('inc') , dec =getId('dec'), interval=null, time=0, min=0;
btn.onclick = startCounter;
inc.onclick = incTime;
dec.onclick = decTime;
function startCounter() {
if (time<=0) {
status.textContent='Increase the timer first!';
time=0;
return;
}
status.textContent='Counting!';
btn.textContent = 'Stop';
btn.onclick = stopCounter;
interval = setInterval(function(){
time--;
if (time<=0) {
stopCounter();
status.textContent='Time\'s Up';
}
setTime();
},200);
}
function stopCounter() {
btn.textContent = 'Start';
btn.onclick = startCounter;
status.textContent='Stopped!';
if (interval) clearInterval(interval);
}
function incTime(){
time++;
setTime();
}
function decTime(){
time--;
setTime();
}
function setTime() {
min= time/60;
if (time<10) s.textContent= '0'+Math.floor(time%60);
else s.textContent= Math.floor(time%60);
if (min<0) m.textContent= '00';
else if (min<10) m.textContent= '0'+Math.floor(min);
else m.textContent= Math.floor(min);
}
function getId(x) {
return document.getElementById(x);
}

Categories