JavaScript countdown - javascript

Why wont it countdown?
<script language="JavaScript" TYPE="text/javascript">
var container = document.getElementById('dl');
var seconds = 10;
var timer;
function countdown() {
seconds--;
if(seconds > 0) {
container.innerHTML = 'Please wait <b>'+seconds+'</b> seconds..';
} else {
container.innerHTML = 'Download';
clearInterval(timer);
}
}
timer = setInterval(countdown, 1000);
</script>
<div id="dl"></div>
<input type="button" onclick="setInterval(countdown, 1000);" id="dl" value="Download" />

Try to move the <script> block after the <div id="dl"></div>.
This way, when document.getElementById('dl'); is executed, the corresponding element in the page will already exist.
With what you posted, when document.getElementById('dl'); is executed, the corresponding <div> is not there yet -- and, so, cannot be found.

Because you are trying to reach the element before it exists, as the code runs before the element is loaded.
Move the line that locates the element inside the function:
<script type="text/javascript">
var seconds = 10;
var timer;
function countdown() {
var container = document.getElementById('dl');
seconds--;
if(seconds > 0) {
container.innerHTML = 'Please wait <b>'+seconds+'</b> seconds..';
} else {
container.innerHTML = 'Download';
clearInterval(timer);
}
}
timer = setInterval(countdown, 1000);
</script>
<div id="dl"></div>
<input type="button" onclick="setInterval(countdown, 1000);" id="dl" value="Download" />

The setInterval takes a string to execute, not a function pointer.
timer = setInterval("countdown()", 1000);

Related

How to handle timer button to not to display negative values on click?

I have a button.
After clicking on it , 10 seconds timer starts on button with changing text.
When i click in between the timer it decrements the value by one.
And at the last shows negative value.
Also when timer becomes zero and i click button it becomes-1 , -2
It should not go below zero.
Tried by many ways but couldn't solve the issue
Here is my code
timeLeft = 10;
function countdown() {
timeLeft--;
$("#tmp_button-72286").text("Download will be ready in "+String(timeLeft)+"seconds");
if (timeLeft > 0) {
setTimeout(countdown, 1000);}
};
function timer(){
$("#tmp_button-72286").text("");
$("#tmp_button-72286").append('<a id="myLink" target="_blank" href="link"><button id="thor">Download Now</button></a>');
}
$("#tmp_button-72286").bind("click", (function () {
countdown();
var timer_var = setInterval(timer, 10 * 1000);
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button id="tmp_button-72286">Download Now</button>
With your script, the user can trigger the countdown every time they click the button. However, the user should just initiate the countdown, and the countdown should then be triggered by itself in 1 second intervals.
To achieve that, you can use a flag to check whether the timer has been initiated or not and trigger the countdown on user click only the first time:
let timeLeft = 10;
function countdown() {
if (timeLeft > 0) {
$("#tmp_button-72286").text("Download will be ready in "+String(timeLeft)+"seconds");
setTimeout(countdown, 1000);
} else {
$("#tmp_button-72286").text("");
$("#tmp_button-72286").append('<a id="myLink" target="_blank" href="link"><button id="thor">Download Now</button></a>');
}
timeLeft--;
};
let timerRunning = false;
$("#tmp_button-72286").bind("click", (function () {
if (!timerRunning) {
timerRunning = true;
countdown();
}
}));
*I also took the liberty to change the trigger of the final message to be when the timeLeft reaches 0 instead of using 2 independent timers, but you can still use your way like this:
let timeLeft = 10;
function countdown() {
timeLeft--
$("#tmp_button-72286").text("Download will be ready in "+String(timeLeft)+"seconds");
if (timeLeft > 0) setTimeout(countdown, 1000);
};
function timer() {
$("#tmp_button-72286").text("");
$("#tmp_button-72286").append(
'<a id="myLink" target="_blank" href="link"><button id="thor">Download Now</button></a>',
);
}
let timerRunning = false;
$("#tmp_button-72286").bind("click", (function () {
if (!timerRunning) {
timerRunning = true;
countdown();
let timer_var = setInterval(timer, 10 * 1000);
}
}));
Try it. I just added variable done to check when function start and prevent from restart function.
let timeLeft = 10;
let done = false;
function countdown() {
timeLeft--;
$("#tmp_button-72286").text(
"Download will be ready in " + String(timeLeft) + "seconds",
);
if (timeLeft > 0) {
setTimeout(countdown, 1000);
}
}
function timer() {
$("#tmp_button-72286").text("");
$("#tmp_button-72286").append(
'<a id="myLink" target="_blank" href="link"><button id="thor">Download Now</button></a>',
);
}
$("#tmp_button-72286").bind("click", function () {
if (!done) {
done = true;
countdown();
var timer_var = setInterval(timer, 10 * 1000);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button id="tmp_button-72286">Download Now</button>
the code can be simplified like this, no need extra variable.
timeLeft = 10;
var tmpButton = $("#tmp_button-72286")
function countdown() {
tmpButton.text("Download will be ready in " + String(timeLeft) + " seconds");
if (timeLeft-- > 0)
setTimeout(countdown, 1000);
else
tmpButton.prop('outerHTML', '<a id="myLink" target="_blank" href="link"><button id="thor">Download Now</button></a>');
};
tmpButton.on("click", countdown);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button id="tmp_button-72286">Download Now</button>

How to initiate this timer with an image button?

I have a 30 second timer and an image. I want the timer to only commence when the image is clicked, i.e. an image button - how do I go about this?
This is how I currently have the timer, with displays on the page itself:
<h2>Countdown left: <span id="timer"></span></h2>
And this is the image:
<img id="img" src="image.gif" />
My timer is JS:
var seconds = 30;
var countdown = setInterval(function() {
seconds--;
document.getElementById("countdown").textContent = seconds;
if (seconds <= 0) clearInterval(countdown);
}, 1000);
How can I combine the two?
You can add click event listener to the image, which will initiate the timer. Also, I have added {once: true} so that the function would execute only once (else it will bug out the timer).
document.querySelector("#img").addEventListener("click", () => {
var countdown;
var seconds = 30;
countdown = setInterval(function() {
seconds--;
document.getElementById("timer").textContent = seconds;
if (seconds <= 0) clearInterval(countdown);
}, 1000)
},{ once: true});
<h2>Countdown left: <span id="timer"></span></h2>
<img id="img" src="https://assets.stickpng.com/thumbs/59060d740cbeef0acff9a660.png" />
If you want to reset the timer on each click, you need to clearInterval before setting another.
var countdown;
document.querySelector("#img").addEventListener("click", () => {
if (countdown) {
clearInterval(countdown);
}
var seconds = 30;
countdown = setInterval(function() {
document.getElementById("timer").textContent = seconds;
seconds--;
if (seconds <= 0) clearInterval(countdown);
}, 1000)
});
<h2>Countdown left: <span id="timer"></span></h2>
<img id="img" src="https://assets.stickpng.com/thumbs/59060d740cbeef0acff9a660.png" />
let timer;
const onClick = () => {
// Initial seconds
let count = 30;
// Element where the count down needs to be displayed
const element = document.querySelector('#timer');
// Remove the timer if it already exists. This would be helpful
// in case the user clicks again on the image. When User clicks
// again on the image, the existing timer is reset
if (timer) {
clearInterval(timer);
}
//Display the initial value i.e. 30 in this case
element.textContent = count;
//Decrease the timer by a second using setInterval
timer = setInterval(() => {
count -= 1;
// If counter is less than or equal to zero, then
// remove the existing count down and perform the logic
// of what should happen when the count down completes
if (count <= 0) {
clearInterval(timer);
element.textContent = '';
return;
}
element.textContent = count;
}, 1000);
}
// Attaches the click event on the image
const image = document.querySelector('#img');
if (image) {
image.addEventListener('click', onClick)
}
<h2>Countdown left: <span id="timer"></span></h2>
<img id="img" src="https://picsum.photos/200" />
If you wrap your existing js in a function, you can add it as a method for the click event listener on the button.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<h2>Countdown left: <span id="timer"></span></h2>
<img id="img" src="image.gif" />
<script>
function count(){
var seconds = 30;
var countdown = setInterval(function() {
document.getElementById("timer").textContent = seconds;
seconds--;
if (seconds < 0) clearInterval(countdown);
}, 1000);
}
document.getElementById('img').addEventListener('click', count)
</script>
</body>
</html>
i think you need to create one function on click of image :
HTML
<img id="img" src="image.gif" onclick="StartTimer()" />
<script type="text/javascript">
function StartTimer() {
var seconds = 30;
var countdown = setInterval(function() {
seconds--;
document.getElementById("countdown").textContent = seconds;
if (seconds <= 0) clearInterval(countdown);
}, 1000);
}
</script>
function startTimer() {
var seconds = 30;
var countdown = setInterval(function() {
seconds--;
document.getElementById("timer").textContent = seconds;
if (seconds <= 0) clearInterval(countdown);
}, 1000);
}
<h2>Countdown left: <span id="timer"></span></h2>
<img id="img" src="image.gif" onClick="startTimer()" />
You can try wrapping the setInterval in a function and call that function on click of image

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>

How to create a countdown timer before a function is performed

What I want to do is have a coin flip which will start a countdown when the flip button is pressed or if instructed to elsewhere. Then I want it to countdown 3, 2, 1 and display that on the screen. When the countdown is complete it will display heads or tails. The reason for this is so I do not have to create an animation of the coin flipping instead a delay to build the tension.
This is the code I have so far:
<html>
<head>
<title>Coin Toss </title>
<script>
function toss() {
if (Math.random()>.5) {
window.document.coin.src = "CT.jpg";
}
else {
window.document.coin.src = "T.jpg";
}
return false;
}
</script>
</head>
<body>
<img name="coin" src="questionmark.png">
<form action="" onSubmit="return toss();">
<input type="submit" value="TOSS">
</form>
</body>
</html>
Here's an example using setTimeout. In this instance I've removed the form as you don't strictly need it imo, and used event listeners so that the JS call is removed from the HTML.
HTML
<img id="coin"/><br/>
<button id="toss">Toss</button><br/>
<div id="count"></div>
JS
function toss() {
var div = document.getElementById('coin');
if (Math.random() > .5) {
coin.src = "CT.jpg";
} else {
coin.src = "T.jpg";
}
}
function countDown() {
var count = 3, timer;
var div = document.getElementById('count');
// if count is not 0, add the new count to the
// count element and loop again, reducing the count number
// otherwise erase the count element, clear the timeout
// and run the toss function
var loop = function loop (count) {
if (count > 0) {
div.textContent = count--;
timer = setTimeout(loop, 1000, count);
} else {
div.textContent = '';
clearTimeout(timer);
toss();
}
}
// start the countdown
loop(count);
}
var button = document.getElementById('toss');
button.addEventListener('click', countDown, false);
DEMO
you can do this with a setInterval, here is an example:
Javascript:
var current = 3;
var elem = document.getElementById('toss');
var intervalId = setInterval( function(){
if( current > 0 ){
elem.innerHTML = "<h1>" + current + "</h1>";
} else {
if( Math.random() > .5 ){
elem.innerHTML = '<img src="http://www.thecoinspot.com/25c/1932%20Type%201%20Silver%20Washington%20Quarter%20Obv.png">';
} else {
elem.innerHTML = '<img src="http://www.thecoinspot.com/25c/1988%20Type%202%20Clad%20Washington%20Quarter%20Reverse.png">';
}
clearInterval( intervalId );
}
current--;
}, 1000 ); // 1000 ms = 1s
HTML:
<div id="toss"><div>
Also here is a Fiddle so you can test it out and see what it does:
http://jsfiddle.net/Cedriking/cLs9r3m6/
For your second question (in the comment), do this:
<html>
<head>
<title>This is my title</title>
</head>
<body>
<div id="toss"></div>
<script type="text/javascript">
var current = 3;
var elem = document.getElementById('toss');
var intervalId = setInterval( function(){
if( current > 0 ){
elem.innerHTML = "<h1>" + current + "</h1>";
} else {
if( Math.random() > .5 ){
elem.innerHTML = '<img src="http://www.thecoinspot.com/25c/1932%20Type%201%20Silver%20Washington%20Quarter%20Obv.png">';
} else {
elem.innerHTML = '<img src="http://www.thecoinspot.com/25c/1988%20Type%202%20Clad%20Washington%20Quarter%20Reverse.png">';
}
clearInterval( intervalId );
}
current--;
}, 1000 ); // 1000 ms = 1s
</script>
</body>
</html>

increment value of a number with a specific timer-value

I've tried and looked around but I could not find anything similar.
<div> <span>23</span>/ 30 </div>
My thought process here is that I want 23 to increment in 1 value every 15th second.
And when it hits 30, it shall stop counting. I have no idea how to make it "stop" counting and how I should approach a problem like this.
Any help would be much appreciated!
Here is a possible solution, note that I do an iteration every second for the demo, but you can lower the rate by doing setTimeout(count,15000);.
var wrapper, value, timer;
window.addEventListener('load', startCounter, false);
function startCounter(){
document.querySelector('button').onclick = startCounter;
wrapper = document.querySelector('span');
value = 22;
count();
}
function count(){
clearTimeout(timer);
value++;
wrapper.innerHTML = value;
if(value < 30){ timer = setTimeout(count,1000); }
}
<div> <span>23</span>/ 30 </div>
<button>reset</button>
<div id="show"></div>
<script>
function timer(){
var i = 0;
setInterval(function(){
i++;
document.getElementById("show").innerHTML = i;
if(i > 30){
i = 0;
}
},1000);
}
timer();
</script>
//just super simple hope can be inspiration done thank
If a class is added to the span element like so:
<div> <span class="counter">23</span>/ 30 </div>
Then this javascript code would work:
var currentCount = parseInt($('.counter').text());
var increaseCount = function() {
if (currentCount < 30) {
currentCount = currentCount + 1;
$('.counter').text(currentCount);
setTimeout(increaseCount, 15000);
}
return;
};
setTimeout(increaseCount, 15000);
Here is an example with the timer set to a second:
https://jsfiddle.net/aqe43oLa/1/
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var i = 24;
var timer=setInterval( increment, 15000);
function increment(){
if(i<=30)
{
console.log(i);
$('.increase').html('').append(i);
i++;
}
else
{
clearInterval(timer);
}
}
</script>
</head>
<body>
<div><span class="increase">23</span>/ 30 </div>
</body>
</html>

Categories

Resources