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;
?>
Related
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);
Here is the JavaScript countdown code for Quiz:
var isClicked;
isClicked = false;
document.getElementById('quiz_button').onclick = function() {
isClicked = true;
};
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
const interval = setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (timer !== 0) {
--timer;
<?php
// start the time session...
Session::set('startTime', time());
?>
} else if (timer == 0) {
if( isClicked == false ) {
$( "#quiz_button" ).trigger( "click", function () {
clearInterval(interval);
});
} else {
clearInterval(timer);
}
}
}, 1000);
}
window.onload = function () {
var seconds = 10,
display = document.querySelector('#time');
startTimer(seconds, display);
};
when the page is load then countdown started.
There is a quiz_button to complete the quiz. When it's clicked I set it true using JS. Otherwise, it triggers the button continuously.
But when the quiz is completed by pressing the button then countdown is still counting. I need to stop it. How can I stop it?
I did:
} else {
clearInterval(timer);
}
I've run the code multiple times trying to fix any error I have found in the code but it just doesn't seem to work.
I'm using the setInterval() loop. The function does not even run once. What could the problem be?
function stopWatch () {
var hours = Number(document.getElementById('hours').innerHTML);
var minutes = Number(document.getElementById('minutes').innerHTML);
var seconds = Number(document.getElementById('seconds').innerHTML);
if (seconds<60) {
seconds++
} else {
seconds = 0;
minutes++
}
if (minutes == 60) {
minutes = 0;
hours++
}
if (seconds.length==2) {
document.getElementById('seconds').innerHTML = seconds;
} else {
document.getElementById('seconds').innerHTML = '0' + seconds;
}
if (minutes.length==2) {
document.getElementById('minutes').innerHTML = minutes;
} else {
document.getElementById('minutes').innerHTML = '0' + minutes;
}
if (hours.length==2) {
document.getElementById('hours').innerHTML = hours;
}
if (hours.length==1) {
document.getElementById('hours').innerHTML = '0' + hours;
}
}
setInterval(stopWatch,1000)
<html>
<head></head>
<body>
<p>
<span id='hours'>00</span>:<span id='minutes'>00</span>:<span id='seconds'>00</span>
</p>
</body>
</html>
Your code only runs once. You need to use a loop of some description.
There are many ways to do this. A simple example would be to use setInterval to call the inners of your function every second.
You also have an error in your logic. You shouldn't be checking the length of the number (seconds.length==2). You should check wether the number is greater than 9 (seconds > 9):
function stopWatch() {
setInterval(function() {
var hours = Number(document.getElementById('hours').innerHTML);
var minutes = Number(document.getElementById('minutes').innerHTML);
var seconds = Number(document.getElementById('seconds').innerHTML);
if (seconds < 60) {
seconds++
} else {
seconds = 0;
minutes++
}
if (minutes == 60) {
minutes = 0;
hours++
}
if (seconds > 9) {
document.getElementById('seconds').innerHTML = seconds;
} else {
document.getElementById('seconds').innerHTML = '0' + seconds;
}
if (minutes > 9) {
document.getElementById('minutes').innerHTML = minutes;
} else {
document.getElementById('minutes').innerHTML = '0' + minutes;
}
if (hours > 9) {
document.getElementById('hours').innerHTML = hours;
} else {
document.getElementById('hours').innerHTML = '0' + hours;
}
}, 1000);
}
stopWatch()
<html>
<head></head>
<body>
<p>
<span id='hours'>00</span>:<span id='minutes'>00</span>:<span id='seconds'>00</span>
</p>
</body>
</html>
You mean why the stopwatch is not running?
You should wrap it in a setInteraval for it to update every second:
setInterval(function() {
stopWatch()
},1000);
i keep getting error said: Cannot set property 'innerHTML' of null.
i try to change innerHTML ->innerText. still not working.
what am i missing here???
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counter = document.getElementById("timer");
var current_minutes = mins-1;
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
if(mins > 1){
// countdown(mins-1); never reach “00″ issue solved:Contributed by
Victor Streithorst
setTimeout(function () { countdown(mins - 1); }, 1000);
}
}
}
tick();
}
countdown(3);
html
<div id="timer"></div>
You're calling countdown(), which calls tick(), which calls document.getElementById("timer"), before that element has even been parsed.
Try doing it like this:
<div id="timer"></div>
<script type="text/javascript">
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counter = document.getElementById("timer");
var current_minutes = mins-1
seconds--;
counter.innerHTML = current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
if(mins > 1) {
// countdown(mins-1);
setTimeout(function () { countdown(mins - 1); }, 1000);
}
}
}
tick();
}
countdown(3);
</script>
In this case, order matters. You want to make sure the document has encountered that element before accessing it via the DOM.
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);
}