Countdown function doesn't display last number in 3-2-1 countdown - javascript

Pretty much what the title says. When the countdown starts, it goes "3", "2", and then executes the function that's supposed to launch when the timer hits zero, skipping the display of the number "1".
The actual timer output is displayed in a separate div element, you'll see in my code below.
I've seen some answers on here about faulty countdown clocks but a lot of them use jQuery whereas I'm just using vanilla JavaScript and the use of libraries is still a bit confusing to me.
var count = 3;
function startTimer() {
var timer = setInterval(function() {startTimer(count);}, 1000);
if(count === 0){
clearInterval(timer);
ranCoord(); //function to run when timer hits zero.
} else {
document.getElementById("target").innerText = count;
count--;
}
}
<div class="start">
<img src="images/start-default.png" onclick="startTimer();" alt="Click Here"/>
</div>
<div id="target"></div>
I noticed that if I include the var count=3 variable inside the startTimer(); function, the countdown doesn't work either, it just stays at number 3. Does anyone know why this is?
Also, if I include the var timer = setInterval(function() {startTimer(count);}, 1000); outside the function then it runs automatically on page load, which is not what I want. I want the countdown to start on the click of a button, and found that this worked when placed inside the function.
Thanks in advance!

If the count variable is declared inside of the startTimer function, then each iteration of the timer will have its count value overwritten and so will not count down.
setInterval repeats its function indefinitely, so only needs to be called once outside of the loop, as opposed to setTimeout which only runs once and needs to be called each iteration.
An alternative approach using setTimeout would be:
function startTimer(count) {
if (count <= 0) {
ranCoord();
} else {
document.getElementById("target").innerText = count;
setTimeout(function() { startTimer(--count); }, 1000);
}
}
This version also avoids the use of a global variable, by passing the remaining count in as a parameter.

You dont need to call startTimer in the setInterval
var count = 3;
function startTimer() {
var timer = setInterval(function() {
if (count === 0) {
clearInterval(timer);
ranCoord(); //function to run when timer hits zero.
} else {
document.getElementById("target").innerText = count;
count--;
}
}, 1000);
}
function ranCoord() {
console.log("Timer hit 0")
}
img {
height: 100px;
width: 100px;
outline: 1px solid blue;
}
<div class="start">
<img src="images/start-default.png" onclick="startTimer();" />
</div>
<div id="target"></div>

I think you not need to add more code you just need to simplify it like that
var count = 3;
function startTimer() {
const timer = setInterval(function () {
document.getElementById("target").innerText = count;
count--;
if (count <= 0) {
clearInterval(timer);
ranCoord();
}
}, 1000)
}

Related

read div and check for a click condition

let timer = document.querySelector("#timer");
var counter = 3;
function myFn() {
counter--
if (counter === -1) {
counter = 3
}
timer.innerText = counter
}
btn.onclick = function() {
text.innerHTML += 'clicked' + '<br>'
}
var myTimer = setInterval(myFn, 1000);
<div id="timer"></div>
<button id="btn">Button</button>
<div id="text"></div>
I'm trying with this small code to read the div#timer every second and check for a click condition in console.log() F12. It gives me different error in every way I try to do it.
let timer = document.querySelector("#timer");
let btn = document.querySelector("#btn");
setInterval(() => {
console.log(timer.textContent)
if (timer.textContent === '0') {
btn.click()
}
}, 1000);
Consider the following jQuery example.
$(function() {
var timer = 0;
var counter = 3;
var timeObj = $("#timer");
var btnObj = $("#btn");
var txtObj = $("#text");
var interval;
function myFn() {
if (--counter >= 0) {
txtObj.append("Clicked<br />");
} else {
clearInterval(interval);
}
}
interval = setInterval(function() {
timeObj.html(++timer);
}, 1000);
btnObj.click(myFn);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="timer">0</div>
<button id="btn">Button</button>
<div id="text"></div>
You will want to use setInterval() and not setTimeout().
The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.
This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
See more: https://developer.mozilla.org/en-US/docs/Web/API/setInterval
Using the -- and ++ before the variable will also apply the change before it is used.
The decrement operator (--) decrements (subtracts one from) its operand and returns the value before or after the decrement, depending on where the operator is placed.
Adjusting the logic here can also ensure that the button click does allow the user to keep performing actions.

Jquery Timer that starts and stops with same button

I can't for the life of my figure out how to get this to work bug free.
The button in the code below needs to do three things.
Start a countdown when clicked (works)
End the countdown automatically, and reset itself when it reaches 0(works)
Reset itself prematurely if its clicked in the middle of a countdown(works, sort of)
Bug: when clicked repeatedly it starts multiple countdowns, and more or less breaks. It needs to either reset itself or start a countdown if clicked repeatedly. There should never be more than one countdown.
It works fines as long as people press the button, wait a second, and then press it again to stop it.
The bug I'm running into is if someone spam clicks it, it starts multiple countdowns and generally just breaks the button. I've tried a lot of different methods to fix it, and this is the closest I've gotten.
var i = 29;
let running=false;
$("#startButton").click(function () {
if(running==false){
var countdown = setInterval(function () {
$("#startButton").text("Reset Timer");
running=true;
$("#stopWatch").html(i);
i--;
if (i <0)
{
$("#startButton").text("Start Timer");
running=false;
clearInterval(countdown);
i = 29;
$("#stopWatch").html(i);
}
$("#startButton").click(function () {
$("#startButton").text("Start Timer");
running=false;
clearInterval(countdown);
i = 29;
$("#stopWatch").html(i+1);
});
}, 1000);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stopWatch">30</div>
<button id="startButton">Start Timer</button>
Welcome to Stack Overflow #William!
I'm not sure what this means: Reset itself prematurely if its clicked in the middle of a countdown(works, sort of). But I managed to fix your bug on spamming button click and for item 3, i just do reset the countdown from initial state. See snippets below:
// Get attribute value from div `stopwatch`. This is for resetting from default value.
var initial = $('#stopWatch').attr("value");
// Assigned initial value to var i.
var i = initial;
$("#stopWatch").html(i);
let running = false;
// Created a separate function to call from button click.
function run(timer = true) {
if (timer) {
running = true;
$("#startButton").text("Reset Timer");
$("#stopWatch").html(i);
var countdown = setInterval(function () {
i--;
$("#stopWatch").html(i);
if (i <= 0) {
running = false;
$("#startButton").text("Start Timer");
clearInterval(countdown);
i = initial;
$("#stopWatch").html(i);
}
}, 1000);
} else {
running = false;
clearInterval(countdown);
i = 0;
$("#startButton").text("Start Timer");
}
}
$("#startButton").click(function () {
// Check if its not running and var i is not 0
if(!running && i != 0) {
run();
// Check if its running and var i is not 0 to ensure that if someone spam the button it just reset the countdown.
} else if (running && i != 0) {
// Will return the else{} on function run().
run(false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stopWatch" value="30"></div>
<button id="startButton">Start Timer</button>
Added some comments on the snippet. Feel free to ask if you have any questions.

Javascript Countdown that loads ahref

I'm totally a beginner with JavaScript and I'm trying to make a Javascript Countdown that loads an
I'm using this code for the countdown
<script language="Javascript">
var countdown;
var countdown_number;
function countdown_init() {
countdown_number = 11;
countdown_trigger();
}
function countdown_trigger() {
if(countdown_number > 0) {
countdown_number--;
document.getElementById('countdown_text').innerHTML = countdown_number;
if(countdown_number > 0) {
countdown = setTimeout('countdown_trigger()', 1000);
}
}
}
function countdown_clear() {
clearTimeout(countdown);
}
</script>
I want to load exactly this after the count reaches 0... I am totally lost... what should I do?
It is basically a countdown that stops a music player after reaching 0. I would like to set up several countdowns with 10 mins, 15 mins, and 30 mins.
var countdown;
var countdown_number;
function countdown_init(time) {
countdown_number = time;
countdown_trigger();
}
function countdown_trigger() {
if (countdown_number > 0) {
countdown_number--;
document.getElementById('countdown_text').innerHTML = countdown_number;
setTimeout('countdown_trigger()', 1000)
} else { // when reach 0sec
stop_music()
}
}
function stop_music(){
window.location.href = "bgplayer-stop://"; //will redirect you automatically
}
Here is a simple example using mostly what you had above. This will need to be expanded a bit in order to have multiple countdowns but the general idea is here.
Fiddle: http://jsfiddle.net/zp6nfc9b/5/
HTML:
<a id="link_to_click" href="bgplayer-stop://">link</a>
<span id="countdown_text"></span>
JS:
var countdown_number;
var countdown_text = document.getElementById('countdown_text');
var link_to_click = document.getElementById('link_to_click');
function countdown_init() {
countdown_number = 11;
countdown_trigger();
}
function countdown_trigger() {
countdown_number--;
countdown_text.innerHTML = countdown_number;
if (countdown_number > 0) {
setTimeout(
function () {
countdown_trigger();
}, 1000
);
}
else {
link_to_click.click();
}
}
link_to_click.addEventListener('click',
function () {
countdown_text.innerHTML = 'link was clicked after countdown';
}
);
countdown_init();
To explain some portions a little I think overall you had the correct idea.
I only added the eventListener so you could see the link was actually being clicked and displays a message in the countdown_text for you.
You didn't need to check countdown_number more than once so I removed that if block.
Also you don't really need to clear the timeout either. It clears itself once it executes. You only really need to clear a timeout if you want to stop it before it completes but since we rely on the timeout completing in order to do the next step its not necessary.

Countdown in JS

I'm trying to have, on a registered.php page, a countdown that shows a timer that starts from 3 secs and goes down second by second, redirecting to another page in the end.
However, when I load the page in my browser i'm redirected to the other page in an instant. Can someone help me figure out why?
The registration was successful, you will be redirected in <span id="num"></span> seconds.
<script>
$(document).ready(function (){
for (var i = 3; i>0; i--) {
setTimeout(function () {
$("#num").html(i);
},1000);
}
window.location.replace("login.html");
});
</script>
Since this is a redirection page, you might not want to include the whole jQuery library for this bit of code:
var remaining = 3;
function countdown() {
document.getElementById('num').innerHTML = remaining;
if (!remaining--) {
window.location.replace("login.html");
}
setTimeout(countdown, 1000);
}
window.onload = countdown;
JS Fiddle Demo
Proper way:
$(document).ready(function () {
var i = 3;
$("#num").html(i);
setInterval(function () {
if(i==0){window.location.replace("login.html");}
i--;
$("#num").html(i > -1 ? i : 0);
}, 1000);
});
setInterval would execute every second the function, but with the code you had, you just set setTimeout to execute after a second, but it didn't stop you from looping further. So you immediately had three timeouts set and then redirected.
$(document).ready(function () {
var timer = 3;
var clearTime = setInterval(function(){
$("#num").html(timer--);
if(timer == 0){
window.clearInterval(clearTime);
window.location.replace("login.html");
}
},1000);
});

Countdown function isn't actually counting down

I have a function in my .js file that is supposed to display a countdown from 10 - 0. Once it hits 0, it should open up a second page. I don't have the part where it opens the page written yet, but that isn't my current problem. My problem is that the countdown will display the number 1, and do nothing else. I'm not really sure why.
Here's the countdown function
function startCountdown() {
for (var i = 10; i >= 0; i--) {
document.getElementById("countdown").value = i;
}
}
Here is the function that calls it
function startAdPage() {
setInterval(changeAd(), 2000);
setInterval(startCountdown(), 1000);
}
Finally, here is the HTML code that it is sending to. Everything is started by the body tag calling the onload method. I know that part works, since I have it doing something else that is working properly.
<div id="counter">
<p>The Central Valley Realtors home page will display in
<input type="text" value="" class="countdown"/>
seconds</p>
</div>
The first argument to setInterval is a function. You're not passing the function, you're calling the function and passing whatever it returns, since you have () after the function name.
Also, you're not waiting between updates to the countdown field. Javascript is single-threaded, the page doesn't update until the script returns. You need this:
function startAdPage(){
var curCounter = 10;
function startCountdown() {
document.getElementById("countdown").value = curCounter;
curCounter--;
if (curCounter == 0) {
clearInterval(countdownInterval);
}
}
setInterval(changeAd, 2000);
var countdownInterval = setInterval(startCountdown, 1000);
}
Your loop inside of startCountdown is running all the way to the end of the loop, so the value ends up 0. Also, you are supposed to pass either an Anonymous function or an unexecuted function to setInterval and clearInterval without parameters. When you add () at the end of a function name you are executing the function. Change the the <input type='text' class='countdown' /> to <input type='text' id='countdown' />, then try the following:
function countdown(begin, end, interval, outputElement){
var repeat = setInterval(function(){
if(outputElement.innerHTML){
outputElement.innerHTML = begin--;
}
else{
outputElement.value = begin--;
}
if(begin === end)clearInterval(repeat);
}, interval);
}
countdown(10, 0, 1000, document.getElementById('countdown'));

Categories