Create a simple 2 minutes countdown - javascript

I want to make a count of 2 minutes, but I want to give you click to the button "Start", so far, and managed to make it work, but I have an error in the minutes does not run as well back but that appears NaN:seconds.
I show them the code that i am working on.
var timeoutHandle;
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 ) {
timeoutHandle=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);
}
document.getElementById("timer").innerHTML = "Finished"
}
}
tick();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="tempo-completo">
<div id="timer">2:00</div>
<button onclick="countdown()">INICIAR</button>
</div>

You are not passing in the number of minutes to the countdown() function.
var timeoutHandle;
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 ) {
timeoutHandle=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);
}
document.getElementById("timer").innerHTML = "Finished"
}
}
tick();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="tempo-completo">
<div id="timer">2:00</div>
<button onclick="countdown(2)">INICIAR</button>
</div>

Jeremy Harris' answer is working perfectly fine, but i would like to propose another one.
Don't use setTimeout to make an interval function, use setInterval. Using setTimeout with a recursive loop is overall less precise
With that in mind i've tweek your code to incorporate this idea.
var timeoutHandle;
function countdown(minutes) {
var seconds = 60;
var mins = minutes
var counter = document.getElementById("timer");
var current_minutes = mins-1
// we create an interval variable to clear it later
// we also use an arrow function to have access to variable
// outside of the current function's scope.
let interval = setInterval(() => {
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
// our seconds have run out
if(seconds <= 0) {
// our minutes have run out
if(current_minutes <= 0) {
// we display the finished message and clear the interval so it stops.
counter.innerHTML = "Finished"
clearInterval(interval);
} else {
// otherwise, we decrement the number of minutes and change the seconds back to 60.
current_minutes--;
seconds = 60;
}
}
// we set our interval to a second.
}, 1000);
}
<div class="tempo-completo">
<div id="timer">2:00</div>
<button onclick="countdown(2)">INICIAR</button>
</div>

Related

stopwatch not functioning properly

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>

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");
}
}
});

How to start a eggtimer after clearInterval()?

A have an eggtimer which can be stopped after clicking on the button "stop". What I want is making this timer working again (from the point where it stopped) after clicking "cancel" in a confirm box. Any sugestions? Thanks for help :)
<!DOCTYPE html>
<html>
<body onload="timer();">
<button onclick="exit();">stop</button>
<p id="seconds">30</p>
<script type="text/javascript">
var clock;
function timer () {
var start = new Date().getTime();
clock = setInterval(function() {
var seconds = Math.round(30 - (new Date().getTime() - start) / 1000);
if (seconds >= 0)
document.getElementById('seconds').innerHTML = seconds;
else
clearInterval(clock);
if (seconds==0) {window.location.href="something.com";
return;
}
}, 1000);
}
function exit(){
clearInterval(clock);
var result = confirm("Are you leaving?");
if (result == true) {
window.location.href="somewhere.com";
}
else {
timer();} // <-- ????
}
</script>
</body>
</html>
You can create a variable that holds in what seconds you are ;
var sec = seconds;
Change your function timer with the timer you want to start as a paramerter
function timer (time)
var clock;
var sec;
function timer (time) {
var start = new Date().getTime();
clock = setInterval(function() {
var seconds = Math.round(time - (new Date().getTime() - start) / 1000);
sec = seconds;
if (seconds >= 0){
document.getElementById('seconds').innerHTML = seconds;
}
else{
clearInterval(clock);
}
if (seconds==0){
window.location.href="something.com";
return;
}
}, 1000);
}
function exit(){
clearInterval(clock);
var result = confirm("Are you leaving?");
if (result == true) {
window.location.href="somewhere.com";
}
else {
console.log(sec);
timer(sec);} // <-- ????
}
<body onload="timer(30);">
<button onclick="exit();">stop</button>
<p id="seconds">30</p>
</body>
Here's a working example.
I moved the seconds variable outside the function so it persists and can be used to re-start the timer.
Also, I added an argument to the timer() function so the count down amount can be changed.
Note that the granularity is at the second level, so the actual count down time might eventually be longer than 30 seconds, but I believe it is acceptable in this use case.
var clock;
var seconds;
function timer(wait) {
var start = new Date().getTime();
clock = setInterval(function() {
seconds = Math.round(wait - (new Date().getTime() - start) / 1000);
if (seconds >= 0)
document.getElementById('seconds').innerHTML = seconds;
else
clearInterval(clock);
if (seconds == 0) {
window.location.href = "something.com";
return;
}
}, 1000);
}
function exit() {
clearInterval(clock);
var result = confirm("Are you leaving?");
if (result == true) {
window.location.href = "somewhere.com";
} else {
timer(seconds);
} // <-- ????
}
timer(30);
<button onclick="exit();">stop</button>
<p id="seconds">30</p>

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);

getting error: Cannot set property 'innerHTML' of null

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.

Categories