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);
}
Related
How can I change my display so instead of calculating seconds it calculates the minutes because when I tried to do the remminuts it did not work and im not quite sure where i am going wrong.
Here is the code for the javascript:
const container = document.querySelector('.counter');
const buttonsDiv = document.querySelector('.buttons');
const secInput = document.getElementById('seconds');
var seconds;
var remseconds;
var minuts;
var toCount = false;
function toSubmit(){
display('start');
remove('seconds');
remove('ok');
seconds = Number(secInput.value);
counting();
}
function display(e){
document.getElementById(e).style.display = 'block';
}
function remove(e){
document.getElementById(e).style.display = 'none';
}
function check(stat){
if(stat.id == "start"){
display("stop");
remove("start");
toCount = true;
}
else if(stat.id == "stop"){
display("continue");
remove("stop");
toCount = false
}
else{
display("stop");
remove("continue");
toCount =true;
}
}
function count(){
if(seconds > 0){
if(toCount == true){
seconds--;
remseconds = seconds % 60;
minuts = Math.floor(seconds / 60);
if(minuts < 10){
minuts = "0" + minuts;
}
if(remseconds < 10){
remseconds = "0" + remseconds;
}
container.innerHTML = minuts + " : " + remseconds;
}
}
else{
container.innerHTML = "DONE!";
buttonsDiv.style.opacity = "0";
}
}
function counting(){
remseconds = seconds % 60;
minuts = Math.floor(seconds / 60);
if(remseconds < 10){
remseconds = "0" + remseconds;
}
container.innerHTML = minuts + " : " + remseconds;
setInterval(count, 1000);
}
As you can see it's calculating for the seconds, but when I tried minutes instead, I got no results from it so i am very stuck on what i might be doing wrong.
If you don't really care about accuracy you can use a function like this:
const secs = x => Math.round(x/60)
This however calculates 0 (mins) when you enter 29 (seconds). If you don't like that search for a more sophisticated solution online.
I'm just starting with javascript, I've been trying to make a simple stopwatch, I found a couple of ways to do it , then I came across this function ... the code doesn't work as a stopwatch unless we return a function , can somebody help me understand why????
for (var i = 1; i <= 5; i++) {
var tick = function(i) {
return ()=>{console.log(i);}
};
setTimeout(tick(i), 500 * i);
}
You should use setInterval and clearInterval for your case.
var i = 10;
var tick = function(i) {
return ()=>{
console.log(i--);
if(i == 0) clearInterval(timer);
}
};
var timer = setInterval(tick(i), 500);
If you want to have stopwatch, you can clearInterval in stop button click event
function stop(){
clearInterval(timer);
}
Update:
I combined Start and Stop in only one button using addEventListener and removeEventListener
var i = 1;
var timer;
var tick = function(i) {
return ()=>{
console.clear();
console.log(i++);
//if(i == 0) clearInterval(timer);
}
};
function start(){
document.getElementById("start").disabled = true;
document.getElementById("stop").disabled = false;
timer = setInterval(tick(i), 500);
}
function stop(){
clearInterval(timer);
document.getElementById("stop").disabled = true;
document.getElementById("start").disabled = false;
}
(function() {
document.getElementById("start2").addEventListener("click", start2);
})();
function start2(){
timer = setInterval(tick(i), 500);
document.getElementById("start2").innerHTML = "Stop";
document.getElementById("start2").removeEventListener("click", start2);
document.getElementById("start2").addEventListener("click", stop2);
}
function stop2(){
clearInterval(timer);
document.getElementById("start2").innerHTML = "Start";
document.getElementById("start2").removeEventListener("click", stop2);
document.getElementById("start2").addEventListener("click", start2);
}
<button id="start" onclick="start()">Start</button>
<button id="stop" onclick="stop()">Stop</button>
<h2>Combine Start and Stop</h2>
<button id="start2" >Start</button>
Because setTimeout first parameter has to be a function.
Your code works because it immediately executes the tick(i) function, which returns a function and that one is used 500ms later as callback.
below code will help you
<h1><time>00:00:00</time></h1>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
</pre>
<script>
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 0,
t;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
start.onclick = function(){
timer();
start.disabled=true;
}
/* Stop button */
stop.onclick = function() {
clearTimeout(t);
start.disabled=false;
}
/* Clear button */
clear.onclick = function() {
h1.textContent = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
}
</script>
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);
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");
}
}
});
http://jsfiddle.net/vvccvvcc/mu45bptk/
how do I pause the timer? I want it to stop when it gets to 5 seconds
I tried this as seen in the fiddle
else {
isWaiting = true;
seconds--;
if (seconds == 5) {
seconds=seconds;}
}
does not work
The timer is initialized by setInterval(GameTimer, 1000);
if (seconds == 5) {
clearInterval(countdownTimer);
} else {
seconds--;
}
You will need to clear the interval in order to stop calling the function. Alternatively if you don't want to clear the interval you can say
if (seconds > 5) {
seconds--;
}
The way you've written it, second is decreased regardless of the condition (since it's before the if statement) and therefore, second = second becomes irrelevant.
Is this what you are looking for?
Fiddle: http://jsfiddle.net/mu45bptk/2/
var isWaiting = false;
var isRunning = false;
var seconds = 10;
var countdownTimer;
var finalCountdown = false;
function GameTimer() {
if (isWaiting) {
return;
}
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) {
if (finalCountdown) {
clearInterval(countdownTimer);
} else {
finalCountdown = true;
}
} else {
if (seconds == 5) {
isWaiting = true;
} else {
seconds--;
}
}
}
countdownTimer = setInterval(GameTimer, 1000);
You need to set isWaiting only if seconds == 5 and then check isWaiting on every run of GameTimer()