Javascript timer breaking when put in loop - javascript

So I am trying to make a timer on Javascript, I'm new so it is very basic. I have it working so that the minutes and the seconds change correctly but when I try to do it in a loop it messes it up. Any help would be great.
var seconds = 5;
var minutes = 3;
function countdown() {
for (i = 0; i < 3; i++) {
if (seconds > 0) {
seconds--;
setTimeout("countdown()", 1000);
} else if (seconds <= 0) {
minutes--;
seconds = 5;
}
}
document.getElementById("timer").innerHTML = minutes + "M " + seconds + "S";
}
countdown();
<p id="timer"></p>

function startCountdown(minutes, seconds) {
updateElement()
var timerId = setInterval(function() {
if(--seconds < 0) {
seconds = 59
--minutes
}
if(minutes <= 0 && seconds <=0 ) {
clearInterval(timerId)
minutes = seconds = 0
}
updateElement()
}, 1000);
function updateElement() {
document.getElementById("timer").innerHTML = minutes + "M " + seconds + "S"
}
}
startCountdown(5, 3)
<p id="timer"></p>

Related

timer is not stopped when it reaches zero

I'm trying to build a timer that when it reaches zero it stops. I've tried to make it with a clearInterval but it is not working. As it does nothing.
function startGame() {
var minute = 00;
var sec = 10;
const timeInterval = setInterval(function() {
document.getElementById("gameTimer").innerHTML =
minute + " : " + sec;
sec--;
if (sec == 00) {
minute--;
sec = 59;
if (minute == 00) {
minute = 0;
clearInterval(timeInterval)
}
} else if (minute == 0 && sec == 1) {
document.getElementById("finishGame").innerHTML = "hello"
}
}, 1000);
};
<span id="gameTimer"></span>
<button onClick="startGame()">Start Counter</button>
<span id="finishGame"></span>
You need to use minute <= 0 condition, since you subtract one from minute first, and then check for minute == 0, which will be false, since minute will be -1.
Also, its better to put all if conditions first, then subtract one from second.
function startGame() {
var minute = 0;
var sec = 10;
const timeInterval = setInterval(function() {
document.getElementById("gameTimer").innerHTML = minute + " : " + sec;
if (sec <= 0) {
minute--;
sec = 59;
if (minute <= 0) {
minute = 0;
clearInterval(timeInterval)
}
} else if (minute == 0 && sec == 1) {
document.getElementById("finishGame").innerHTML = "hello";
}
sec--;
}, 1000);
};
<body>
<span id="gameTimer"></span>
<button onClick="startGame()">Start Counter</button>
<span id="finishGame"></span>
</body>

Stop a Javascript countdown

I'm working on a pomodoro clock, everthing is working well but when the user clicks to run the the counter more than once I get two counters working I would like to pause the counter and not start another.
function countdown(minutes) {
let seconds = 60;
let mins = minutes;
function tick() {
let current_minutes = mins-1;
seconds--;
time.innerHTML = current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
if(mins > 1){
countdown(mins-1);
}
}
console.log(mins);
if (seconds === 0 && mins === 1) {
time.innerHTML = `${sessionLength}:00`;
rounds++;
console.log(rounds);
PlaySound(sound);
}
}
tick();
}
how can I accomplish this?
Why not use setInterval?
var myPomodoro = setInterval(function(){
//... run code in here every 60 seconds
}, 60000);
// stop the timer
clearInterval(myPomodoro);

trying to make a count down with out using date function

this is my code, it doesn't work I think the problem is what I'm returning in the function.
Please, help.
var minutes = 25;
var seconds = 60;
function myFunction() {
var start = setInterval(function() {
if (seconds > 0) {
seconds--;
}
if (seconds == 0) {
seconds = 60;
minutes--;
}
if (seconds == 0 && minutes == 0) {
alert("done");
}
var time = minutes + ":" + seconds;
return time;
}, 1000);
return start;
}
console.log(myFunction());
Description
Minor changes to show your code is working
Bugs?
- Requires a minutes and seconds variable be declared before myFunction is called, the rewrite takes these are parameters.
- Doesn't check if the variables are negative and thereby expects "valid" data from the user.
- Only allows for console.log(time), the rewrite allows a function to be passed in for each tick and onTimerComplete
var minutes = 25;
var seconds = 60;
function myFunction() {
var start = setInterval(function() {
if (seconds > 0) {
seconds--;
}
if (seconds == 0 && minutes == 0) {
alert("done");
// added this to clear the timer on 0 minutes 0 seconds
clearInterval(start);
return;
}
if (seconds == 0) {
seconds = 59;
minutes--;
}
var time = minutes + ":" + seconds;
// adding this as this is the function being repeated
console.log(time);
}, 1000);
}
myFunction();
How I would rewrite this
function timer(minutes, seconds, onTimerChanged, onTimerComplete) {
var timerPointer = undefined;
// if minutes is below 0 reset to 0
if (minutes < 0) {
minutes = 0;
}
// if seconds is set below 0 reset to 0
if (seconds < 0) {
seconds = 0;
} else if (seconds > 59) {
// this will add to minutes if too many seconds are passed
minutes += Math.floor(seconds / 60);
seconds = seconds % 60;
}
// this is the function to be called on each tick call
// default: console.log
if (onTimerChanged === undefined) {
onTimerChanged = console.log;
}
if (onTimerComplete === undefined) {
onTimerComplete = function() {
console.log("done")
};
}
// starts the timer
this.start = function() {
timerPointer = setInterval(tick, 1000);
}
// stops the timer
this.stop = clearInterval(timerPointer);
this.time = undefined;
// function for each tick
function tick() {
if (seconds > 0) {
seconds--;
}
if (seconds == 0 && minutes == 0) {
// added this to clear the timer on 0 minutes 0 seconds
clearInterval(timerPointer);
if (onTimerComplete) {
onTimerComplete();
}
return;
}
if (seconds == 0) {
seconds = 59;
minutes--;
}
// pads the numbers so they are always two digits
this.time = padToTwo(minutes) + ":" + padToTwo(seconds);
// if onTimeChanged exists call it
if (onTimerChanged) {
onTimerChanged(this.time);
}
}
// padding the string to be two digits always
function padToTwo(number) {
if (number <= 99) {
number = ("0" + number).slice(-2);
}
return number;
}
}
// create the timer object
var test = new timer(-1, 500);
// start the timer
test.start();
// this would also work
// new timer(minutes, seconds).start();
Both of the returns you have are pointless. console.log() will only output one time. You have to have console.log() inside of the setInterval() function to run multiple times. You should also clear the interval to avoid any memory leaks.
Last, I also added in minutes > 0 because otherwise seconds would be 60 and minutes would be -1 when time has run out.
var minutes = 25;
var seconds = 60;
function myFunction() {
var start = setInterval(function() {
if (seconds > 0) {
seconds--;
}
if (seconds == 0 && minutes > 0) {
seconds = 60;
minutes--;
} else
if (seconds == 0 && minutes == 0) {
clearInterval(start);
alert("done");
}
var time = minutes + ":" + seconds;
console.log(time);
}, 1000);
}
myFunction();
Your code (almost) works. You just will have to wait 26 minutes to see the alert.
if (seconds == 0 && minutes == 0) {
clearInterval(start);
alert("done");
}

Display minutes and seconds total in Javascript Timer

Everything I have so far is working great, although I'd like an alert that will display the amount of time used on the timer.
Example, starting timer at 00:10 and stopping at -00:20, the message alert should say 30 seconds
My problem is stopTimer() which is the STOP button, on click it should display the amount of seconds, minutes however I'm having trouble with.
How can I form minutes in there as well, if the client went that long? JsFiddle
var totseconds = 10;
var seconds = totseconds;
function floor(x) {
return x | 0;
}
function pad(n) {
if (n < 0) {
n = -n;
}
if (n < 10) {
return '0' + n.toString();
}
return n.toString();
}
function stopTimer() {
clearTimeout(countdownTimer);
if (seconds > 60) {
var rs = seconds % 60;
var m = seconds / 60;
windows.alert((totalseconds / 60) - (m + 1) + " minutes and " + totalseconds - (rs + 1) + " seconds")
}
//else {window.alert((seconds +1)+ " seconds");}
else {
window.alert(totseconds - (seconds + 1) + " seconds");
}
}
function secondPassed() {
var minutes = pad(floor(seconds / 60));
if (seconds < 0) {
minutes = '-' + minutes;
}
var remainingSeconds = pad(seconds % 60);
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds > 0) {
seconds--;
if (seconds > 8) {
document.body.style.backgroundColor = "green";
} else if (seconds == 5) {
document.body.style.backgroundColor = "yellow";
}
} else {
document.body.style.backgroundColor = "red";
if (seconds % 2 == 0) {
document.getElementById('skull').style.display = "block";
}
if (seconds % 2 != 0) {
document.getElementById('skull').style.display = "none";
}
seconds--;
}
}
<img id="skull" src="http://s15.postimg.org/es5w3xpob/skull.gif" style="position:absolute; z-index: -1;display:none;">
<div style=" z-index:10;">
<p align="center"> <span id="countdown" style="color:black; font-size: 50px; font-weight: bold;"></span>
</br>
<button onclick="countdownTimer = setInterval('secondPassed()', 1000)">Start</button>
<button onclick="stopTimer()">Stop</button>
</p>
</div>
Confusion caused by counting seconds backwards seems to be the problem. On the fiddle in function stopTimer() changing
if (seconds > 60) { // .... more than a minute
to
if(seconds < -60) { // ... more than a minute
causes code for over a minute to get executed (which as written has errors and will need debugging). To clarify the logic and make coding easier when counting backwards may I suggest calculating something like
var elapsedSeconds = - (seconds - totseconds);

Javascript 3 minute timer that repeats when complete and shows message at the end of each cycle

I am making a speed dating timer that counts down from 3 minutes to 0, shows a "move on to next date" message, and then repeats.
I have been able to get the timer to count down to 0, and then restart after the interval I've set, but for some reason it will not display the message. My code is as follows
function countdown(element, minutes, seconds) {
// set time for the particular countdown
var time = minutes*60 + seconds;
var interval = setInterval(function() {
var el = document.getElementById(element);
// if the time is 0 then end the counter
if(time == 0) {
el.innerHTML = "Move on to next date...";
clearInterval(interval);
setTimeout(function() {
countdown('clock', 3, 0);
}, 2000);
}
var minutes = Math.floor( time / 60 );
if (minutes < 10) minutes = "0" + minutes;
var seconds = time % 60;
if (seconds < 10) seconds = "0" + seconds;
var text = minutes + ':' + seconds;
el.innerHTML = text;
time--;
}, 1000);
}
countdown('clock', 3, 0);
just try this code i have fixed it for you
<html>
<head>
<Script>
function countdown(element, minutes, seconds) {
// set time for the particular countdown
var time = minutes*60 + seconds;
var interval = setInterval(function() {
var el = document.getElementById('element');
// if the time is 0 then end the counter
if(time == 0) {
setTimeout(function() {
el.innerHTML = "Move on to next date...";
}, 10);
clearInterval(interval);
setTimeout(function() {
countdown('clock', 0, 5);
}, 2000);
}
var minutes = Math.floor( time / 60 );
if (minutes < 10) minutes = "0" + minutes;
var seconds = time % 60;
if (seconds < 10) seconds = "0" + seconds;
var text = minutes + ':' + seconds;
el.innerHTML = text;
time--;
}, 1000);
}
countdown('clock', 0, 5);
</script>
</head>
<body>
<p id="element">elelelelel</p>
</body>
</html>
You're falling through into the "set the time" part again after the 'set the text' part. It is updating the text, but then overwriting it with "00:00".
You should insert a return statement to stop it continuing, or wrap the clock part in an else block.
function countdown(element, minutes, seconds) {
// set time for the particular countdown
var time = minutes*60 + seconds;
var interval = setInterval(function() {
var el = document.getElementById(element);
// if the time is 0 then end the counter
if (time <= 0) {
var text = "hello";
el.innerHTML = text;
setTimeout(function() {
countdown('clock', 0, 5);
}, 2000);
clearInterval(interval);
return;
}
var minutes = Math.floor( time / 60 );
if (minutes < 10) minutes = "0" + minutes;
var seconds = time % 60;
if (seconds < 10) seconds = "0" + seconds;
var text = minutes + ':' + seconds;
el.innerHTML = text;
time--;
}, 1000);
}
countdown('clock', 0, 5);
See fiddle: http://jsfiddle.net/aTDJY/
I got this to work by changing
innerHTML to innerText
In my example the clock is just a div. If you are using textbox you need to use to use value.
Here's my complete solution.
<html>
<head>
<script type="text/javascript">
function countdown(element, minutes, seconds) {
// set time for the particular countdown
var time = minutes*60 + seconds;
var interval = setInterval(function() {
var el = document.getElementById(element);
// if the time is 0 then end the counter
if(time == 0) {
el.innerText = "Move on to next date...";
clearInterval(interval);
setTimeout(function() {
countdown('clock', 3, 0);
}, 10);
}
var minutes = Math.floor( time / 60 );
if (minutes < 10) minutes = "0" + minutes;
var seconds = time % 60;
if (seconds < 10) seconds = "0" + seconds;
var text = minutes + ':' + seconds;
el.innerText = text;
time--;
}, 10);
}
countdown('clock', 3, 0);
</script>
</head>
<body>
<h1>Clock</h1>
<div id="clock"/>
</body>
</html>
I will do it like this instead
$(document).ready(function(){
setInterval(UpdateTime(), 1000);
});
var interval = 3*60; // 3 minutes
function updateTime(){
interval --;
if(interval == 0)
{
$(element).val("Move on to next date...");
var interval = 3*60;
}
else
{
$(element).html(interval + " seconds left");
}
}

Categories

Resources