Why won't my timer function in JS start countdown? - javascript

My countdown timer does not work. I ideally I want it to start when the start buttons is clicked, am I missing something? I've done the event listener on click to the startButton variable, which has a document.getElementById("start-button") to the HTML. I'm not sure why it isn't working.
let countdownDisplay = document.getElementById("countdown-timer");
let startButton = document.getElementById("start-button");
let timer = 60; //document.getElementsByClassName("countdown");
let startGame = document.getElementsByClassName("button");
function countDown () {
setInterval(function(){
if (timer <= 0) {
clearInterval(timer = 0)
}
countdownDisplay.innerHTML = timer
timer -= 1
}, 1000)
}
startButton.addEventListener('click', countDown)
<div id="start-game">
<a class="button" id="start-button" href="quiz.html">Start Game - Kick Off</a>
</div>

Do not use a <a> tag with href attribute since your page will reload to the new url path. Instead just use a button:
As #Scott Marcus said, do not use .innerHTML when the text is not HTML as .innerHTML has security and performance implications. Use .textContent instead.
As #Dave Newton said, the argument to clearInterval should be an interval reference returned by setInterval. So relate the interval to a variable.
let countdownDisplay = document.getElementById("countdown-timer");
let startButton = document.getElementById("start-button");
let timer = 60; //document.getElementsByClassName("countdown");
let startGame = document.getElementsByClassName("button");
function countDown () {
let mytimer = setInterval(function(){
if (timer <= 0) {
clearInterval(mytimer)
}
countdownDisplay.textContent = timer
timer -= 1
}, 1000)
}
startButton.addEventListener('click', countDown)
<div id="start-game">
<button type="button" class="button" id="start-button">Start Game - Kick Off</button>
<br>
<label id="countdown-timer">Start number</label>
</div>

Remove the href attribute from the anchor - it's causing you to leave/reload the page.
let countdownDisplay = document.getElementById("countdown-timer");
let startButton = document.getElementById("start-button");
let timer = 60;
let startGame = document.getElementsByClassName("button");
let t;
function countDown() {
t = setInterval(function() {
if (timer <= 0) {
clearInterval(t)
}
countdownDisplay.innerHTML = timer
timer -= 1
}, 1000)
}
startButton.addEventListener('click', countDown)
<div id="start-game">
<a class="button" id="start-button">Start Game - Kick Off</a>
</div>

seems to be ok to me. I adjusted the html to remove link, add element to display countdown and added log.
I removed link because if you click on link you are navigating away from page.
also you should learn how the snippets work on stack overflow, you will get more answers.
let countdownDisplay = document.getElementById("countdown-timer");
let startButton = document.getElementById("start-button");
let timer = 60; //document.getElementsByClassName("countdown");
let startGame = document.getElementsByClassName("button");
function countDown() {
setInterval(function() {
if (timer <= 0) {
clearInterval(timer = 0);
}
//countdownDisplay.innerHTML = timer;
timer -= 1;
countdownDisplay.innerHTML = timer;
console.log(timer);
}, 1000)
}
startButton.addEventListener('click', countDown)
<div id="start-game">
<a class="button" id="start-button">Start Game - Kick Off</a>
</div>
<div id="countdown-timer" />

Related

how to improve the code with the constructor maybe?

Is my code wrong or is there a more effective way to do what i posted? I don't know how to do it better.
In the code there is a timer that restarts every time when it reaches 0.
A dynamic reading on the div.counter with the condition 'if the counter reaches 0s it must also press the button autonomously.
<body>
<h1>Callback</h1>
<div id="timer"></div>
<button id="btn">Button</button>
<div id="text"></div>
</body>
let timer = document.querySelector("#timer");
let text = document.getElementById('text')
let btn = document.getElementById('btn')
var counter = 3;
function myFn() {
counter--
if (counter === -1) {
counter = 3
}
timer.innerText = counter
}
var myTimer = setInterval(myFn, 1000);
setInterval(() => {
time = timer.textContent
console.log(time)
if (time === '0') {
btn.click()
}
}, 1000);
btn.onclick = function () {
text.innerHTML += 'clicked' + '<br>'
}

How to end my countdown timer when a button is clicked?

I'm trying to create a function that will end a countdown timer, or automatically make the minutes and seconds part of the countdown timer === 0; however, it seems that using clearInterval(time) doesn't seem to work! Could anyone point out how I might be able to achieve what I'm trying to do!
Note that I've made startingMinutes = 1 just for my ease.
Below is the countdown function and HTML:
// FUNCTION - countDown function that counts down from 8 minutes
const startingMinutes = 1;
let time = startingMinutes * 60;
function updateCountDown() {
const minutes = Math.floor(time / 60);
let seconds = time % 60;
seconds = seconds < 1 ? '0' + seconds : seconds;
document.getElementById("countdown").innerHTML = `${minutes}:${seconds}`;
time--;
time = time < 0 ? 0 : time;
if (minutes == 0 && seconds == 0) {
document.getElementById('tableStyle').style.display = "block";
document.getElementById('wordsIncluded').style.display = "block";
document.getElementById('show_header_one').style.display = "block";
recognition.abort(); //speech recognition stops when countdown timer ends
isListening = false;
}
//my attempt at clearing the countdowntimer!
window.addEventListener('DOMContentLoaded', function() {
document.getElementById("submit_button").addEventListener("click", function() {
clearInterval(time);
})});
HTML:
//where the countdown timer is displayed
<div id="circle"><p id="countdown">8:00</p></div>
//Click the below button and the countdown timer will end (minutes === 0 and seconds === 0)
<button id="submit_button" type="submit">Click to Submit</button>
To use clearInterval you need to pass it the value returned by setInterval
I have an example below using your code, where I pass the value from "setInterval" which I call "interval" to a function "stop" which calls "clearInterval" to stop the timer, and runs the code you were running.
let isListening = true;
const recognition = { abort: () => console.log('aborted') };
function updateCountDown(time) {
const minutes = Math.floor(time / 60);
const seconds = time % 60;
const timer = document.getElementById("countdown");
timer.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;
}
function start(time) {
const interval = setInterval(() => {
if (--time) updateCountDown(time);
else stop(interval);
}, 1000);
document.getElementById("submit_button")
.addEventListener("click", () => stop(interval))
}
function stop(interval) {
updateCountDown(0); // This line sets time to 0
clearInterval(interval);
foo()
}
// I assume you want this to happen when the timer runs down or the button is clicked
function foo() {
document.getElementById('tableStyle').style.display = "block";
document.getElementById('wordsIncluded').style.display = "block";
document.getElementById('show_header_one').style.display = "block";
recognition.abort(); //speech recognition stops when countdown timer ends
isListening = false;
}
start(8*60)
#tableStyle, #wordsIncluded, #show_header_one { display: none; }
<p id="tableStyle">Table Style</p>
<p id="wordsIncluded">Words Included</p>
<p id="show_header_one">Show Header One</p>
<div id="circle">
<p id="countdown">8:00</p>
</div>
<button id="submit_button" type="submit">Click to Submit</button>
const startingMinutes = 1;
let time = startingMinutes * 60;
var abort_count_down = true;
function updateCountDown() {
if (abort_count_down) {
const minutes = Math.floor(time / 60);
let seconds = time % 60;
seconds = seconds < 1 ? '0' + seconds : seconds;
document.getElementById("countdown").innerHTML = `${minutes}:${seconds}`;
time--;
time = time < 0 ? 0 : time;
if (minutes == 0 && seconds == 0) {
document.getElementById('tableStyle').style.display = "block";
document.getElementById('wordsIncluded').style.display = "block";
document.getElementById('show_header_one').style.display = "block";
recognition.abort(); //speech recognition stops when countdown timer ends
isListening = false;
}
};
//my attempt at clearing the countdowntimer!
window.addEventListener('DOMContentLoaded', function() {
document.getElementById("submit_button").addEventListener("click", function() {
abort_count_down = false;
})});

Reset function by button

I have a button that disappears by a function after one second.
if I click on the button, I want the function will reset and I will get one another second to click. And-I want the button will disappeared if I did not click this second.
(if I click in a second, the button doesn't disappeared, if I miss one second, it is disappeared, but if I click, I'll get another second, and so on...)
This is my code:
HTML:
<button id="btn">click
</button>
JavaScript:
let btn = document.querySelector('#btn');
btn.addEventListener('click', ()=>{
click();
})
setTimeout(function click() {
btn.style.display = ('none');
}, 1000);
That code doesn't work.
I am an absolute beginner, so any feedback will help me.
If my question is not understood, please write to me in the comments or edit the question.
This is my suggestion:
var c = 10;
var timer;
clock();
function clock() {
timer = setInterval(countdown, 1000);
}
function countdown() {
counter.innerHTML = --c;
if (c === 0) {
btn.style.display = 'none';
clearInterval(timer);
}
}
btn.onclick = function() {
clearInterval(timer);
c = 10;
counter.innerHTML = c;
clock();
};
<button id="btn">Click me before it's too late (<span id="counter">10</span>)</button>
Change your javascript to the following:
let btn = document.querySelector('#btn');
btn.addEventListener('click', ()=>{
click();
})
function click() {
setTimeout(function() {
btn.style.display = 'none';
}, 1000);
}
Click was not defined properly :)
You should try jQuery, it'll make your learning a lot easier!
Also press f12 on Google Chrome to show developer console, errors will show up there.
You need to apply the display:none inside setTimeout. Here is an example.
let btn = document.querySelector('#btn');
let time = document.querySelector('#time');
const timeLimit = 10;
let timeoutId, intervalId;
time.innerText = timeLimit;
let startTime;
window.onload = () => {
startTime = Date.now();
startTimer();
removeButton();
}
btn.addEventListener('click', stop);
function stop() {
intervalId && clearInterval(intervalId);
timeoutId && clearTimeout(timeoutId);
}
function startTimer() {
let count = 1;
intervalId = setInterval(() => {
if(count === 10) clearInterval(intervalId);
time.innerText = timeLimit - count;
count++;
}, 1000);
}
function removeButton() {
timeoutId = setTimeout(() => {
btn.style.display = 'none';
}, timeLimit*1000);
}
<button id="btn">Click me. I am disappearing ⏳ <span id="time"></span></button>

How to call another setInterval once one has been completed and then reset to the default time for a Pomodoro Project

I am trying to figure out how to call my "breakValue" once the "defaultClockTime" is "0:00", this is after the start.onclick has been called and the "studyValue" has been completed. I want my studyIterations to increase once the "studyValue" is completed and then once the "breakValue" has also been completed for this to increase also. Once that is done I want it to then redefault back to the original time.
please see codepen
I have tried multiple IF statements to try and create some kind of rule that once that is met to call the breakValue function but the way in which I have it so far is that the code will just keep looping around as the condition of "if (time == -1)" will keep being met and will not break out of that loop? and I cannot figure out a way to resolve my problem
I have looked at multiple pomodoro projects on this site and other's on codepen but their code is not giving me the answer I need as mine is written with vanilla JS and theirs is usually using Jquery or some kind of front end framework.
please can someone help me with this last piece of my project I have spent days trying to figure this out in vanilla JS.
any questions please ask!
<body>
<div id="pomodoroContainer">
<h1 id="heading">Pomodoro Clock</h1>
<div class="timerContainer">
<h2 id="time"><time>25:00</time></h2>
<img id="start" src="./src/img/play-button.svg" height="30px">
<img id="reset" src="./src/img/restart.svg" height="30px">
</div>
<div>
<img id="StudyTomato" src="./src/img/tomato.png">
<span id="studyIterations">0</span>
<img id="breakCoffee" src="./src/img/study.png">
<span id="breakIterations">0</span>
</div>
</div>
<div id="breakAndTimeContainer">
<div id="studyTime">
<h3 id="studyValue"><time>25</time></h3>
<p>Study Time</p>
<button id="decreaseStudyValue">-</button>
<button id="increaseStudyValue">+</button>
</div>
<div id="breakTime">
<h3 id="breakValue"><time>5</time></h3>
<p>Break Time</p>
<button id="decreaseBreakValue">-</button>
<button id="increaseBreakValue">+</button>
</div>
</div>
</body>
<script src="./src/app.js"></script>
clock = document.getElementById('time');
start = document.getElementById('start');
reset = document.getElementById('reset');
studyIterations = document.getElementById('studyIterations');
breakIterations = document.getElementById('breakIterations');
studyValue = document.getElementById('studyValue');
decreaseStudyValue = document.getElementById('decreaseStudyValue');
increaseStudyValue = document.getElementById('increaseStudyValue');
breakValue = document.getElementById('breakValue');
decreaseBreakValue = document.getElementById('decreaseBreakValue');
increaseBreakValue = document.getElementById('increaseBreakValue');
let defaultClockTime = 25;
let time = defaultClockTime * 60;
let studyIterationsValue = 0;
let breakIterationsValue = 0;
let defaultStudyTime = 25;
let defaultBreakTime = 5;
let intervalId;
clockCountdown = () => {
const minutes = Math.floor(time / 60);
let seconds = time % 60;
seconds = seconds < 10 ? '0' + seconds : seconds;
clock.innerHTML = `${minutes}:${seconds}`;
time--;
if (time == -1) {
studyIterationsValue++;
studyIterations.innerHTML = studyIterationsValue;
clearInterval(intervalId);
}
if (time == -1) {
time = defaultBreakTime * 60;
breakIterationsValue++;
breakIterations.innerHTML = breakIterationsValue;
clearInterval(intervalId);
}
}
start.onclick = function () {
intervalId = setInterval(clockCountdown, 1000);
time = defaultClockTime * 60;
}
reset.onclick = function () {
clearInterval(intervalId);
clock.innerHTML = defaultClockTime + ':00'
time = defaultClockTime * 60;
}
breakValue = () => {
intervalId = setInterval(clockCountdown, 1000);
time = defaultBreakTime * 60;
}
increaseStudyValue.onclick = function () {
defaultStudyTime++;
studyValue.innerHTML = defaultStudyTime;
defaultClockTime++
time = defaultClockTime * 60;
clock.innerHTML = defaultClockTime + ':00'
}
decreaseStudyValue.onclick = function () {
defaultStudyTime--;
studyValue.innerHTML = defaultStudyTime;
defaultClockTime--;
time = defaultClockTime * 60;
clock.innerHTML = defaultClockTime + ':00'
}
increaseBreakValue.onclick = function () {
defaultBreakTime++;
breakValue.innerHTML = defaultBreakTime;
time = defaultBreakTime * 60;
}
decreaseBreakValue.onclick = function () {
defaultBreakTime--;
breakValue.innerHTML = defaultBreakTime;
time = defaultBreakTime * 60;
}

Clear Interval + message and replace with a link

How can I clean interval+message and replace those with a link.
Below code is opening a link after 10 seconds in new window. When I get back to that page, message showing You will redirect in 0 seconds
What I want is, after 10 seconds (after opening link in new tab) the counter and message will replace with a new message and link. i.e. If you are not redirected to the link Click Here to go to the link.
var count = 10;
var counter;
function start(){
counter = setInterval(timer, 1000);
}
function timer() {
var output = document.getElementById("displaySeconds");
output.innerHTML = count;
count--;
if (count < 0) {
clearInterval(counter);
window.open("https://www.google.com");
return;
}
}
window.addEventListener("load", start, false);
<br>You will redirect in <span id="displaySeconds">10</span> seconds.<br />
You can create a separate div with the text when the user is not redirected with the display property set to none (display: none). When the timer expires, you can hide the original text and show the alternative version.
There is a working jsfiddle below. I modified the counter to 4 seconds not to wait too much, you can adjust it how you want.
var count = 4;
var counter;
function start() {
counter = setInterval(timer, 1000);
}
function timer() {
var output = document.getElementById("displaySeconds");
output.innerHTML = count;
count--;
if (count < 0) {
clearInterval(counter);
window.open("https://www.google.com");
let originalText = document.getElementById("original");
let noRedirectText = document.getElementById("noredirect");
originalText.style.display = "none";
noRedirectText.style.display = "block";
}
}
window.addEventListener("load", start, false);
<div>
<div id="original">
You will be redirected in <span id="displaySeconds">4</span> seconds.
</div>
<div style="display: none" id="noredirect">
If you are not redirected click here to go to the link.
</div>
</div>
Cheers!
Just add code to the interval function that hides the first message and shows the other.
var count = 5;
var output = document.getElementById("displaySeconds");
var counter = null;
function timer() {
output.textContent = count;
count--;
if (count < 0) {
clearInterval(counter);
window.open("https://www.google.com");
// Hide the first message and show the second:
document.querySelector(".redirect1").classList.add("hidden");
document.querySelector(".redirect2").classList.remove("hidden");
}
}
addEventListener("load", function(){
couner = setInterval(timer, 1000);
});
.hidden { display:none; }
<div class="redirect1">You will redirect in <span id="displaySeconds">5</span> seconds.</div>
<!-- The following is initially hidden because of the CSS class -->
<div class="redirect2 hidden">If you aren't redirected, click here</div>
This function replaces the current text with your required text if the redirect was not able to take place.
var count = 10;
var counter = setInterval(timer, 1000);
var output = document.getElementById("displaySeconds");
var container = document.getElementById("container");
function timer() {
count--;
if (count === 0) {
stopTimer();
}
output.innerHTML = count;
};
function stopTimer() {
clearInterval(counter);
window.open("https://www.google.com");
container.innerHTML = ' If you are not redirected to the link Click Here to go to the link.';
}
<div id="container">
You will redirect in <span id="displaySeconds">10</span> seconds.
</div>

Categories

Resources