Countdown in JS - javascript

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

Related

Javascript Countdown Timer w/ Bootstrap Modal Pause

See my code below, I am trying to get the countdown timer to pause when a bs.modal is shown and to resume again once the modal is hidden. This works perfectly if the modal is opened and then closed but if you try to reopen the modal again, the timer just continues. I am probably missing something obvious but am not the best when it comes to JS.
(function countdown(remaining) {
if(remaining === 0) {
location.reload(true);
}
document.getElementById('countdown').innerHTML = remaining;
$(document).on('shown.bs.modal', function(e) {
console.log("modal triggered");
clearTimeout(timeout);
});
$(document).on('hide.bs.modal', function(e) {
console.log("modal closed");
countdown(remaining - 1);
});
timeout = setTimeout(function(){
if(remaining != 0) {
countdown(remaining - 1);
}
}, 1000);
})(300);
It seems the issue with the existing code is a timing problem that results in multiple timeouts getting set simultaneously, some of which can then never be cleared because their id's get lost. It's easy to get into such a situation when you're setting up a new timeout for every iteration. So, as I mentioned, setInterval() is a better choice here. Below is a solution using setInterval(). Also note that it's written so as to ensure that any existing interval is cleared before its id is overwritten (in the function clearAndSetInterval.)
(function (remaining) {
var interval;
var clearAndSetInterval = function () {
clearInterval(interval);
interval = setInterval(function (){
if (remaining <= 0) {
clearInterval(interval);
location.reload(true);
}
document.getElementById('countdown').innerHTML = remaining;
remaining = remaining - 1;
}, 1000);
};
$(document).on('shown.bs.modal', function(e) {
clearInterval(interval);
});
$(document).on('hide.bs.modal', function (e) {
clearAndSetInterval();
});
clearAndSetInterval();
})(300);

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

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

Javascript clearInterval does not stop setInterval

I have a javascript code that shows some messages every 6 seconds using setInterval function as bellow:
$(function () {
count = 0;
wordsArray = ["<h1>Offer received</h1>", "<h1>Offer reviewed</h1>", "<h1>Decision pending</h1>", "Offer accepted.</h1>"];
setInterval(function () {
$(".lead").fadeOut(400, function () {
$(this).html(wordsArray[count % wordsArray.length]).fadeIn(400);
});
if(count === 3){
clearInterval(window.location.href = "www.mydomain.com");
}
count++;
}, 6000);
});
When the last message is displayed I want to redirect to a URL so I checked the counter and placed a clearInterval when the last message is displayed however it does not go to the url right after the last massage is displayed but geos back to the first one and then redirect, sounds like it continues to loop. How can I fix that please?
Thanks
An interval id is returned by setInterval , you need to use that to stop particular interval.
$(function() {
count = 0;
wordsArray = ["<h1>Offer received</h1>", "<h1>Offer reviewed</h1>", "<h1>Decision pending</h1>", "<h1>Offer accepted.</h1>"];
var intervalTimer = setInterval(function() {
$(".lead").fadeOut(400, function() {
$(this).html(wordsArray[count % wordsArray.length]).fadeIn(400);
});
if (count === 3) {
clearInterval(intervalTimer);
}
count++;
}, 6000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="lead"></div>

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.

Why will my JQuery only run if I place window load function within?

My following code will not function, unless I place it all
$(window).load(function(){
// within here
}
How can I get my code to run without requiring the above function?
Thanks!
My code:
// Player controls
var timer = null;
$('#left').mousedown(function() {
moveLeft(); // Do it now
timer = setInterval(moveLeft, 5); // Then every 100 ms
}).mouseup(function() {
clearInterval(timer); // And stop it
});
function moveLeft() {
var nextpos = parseInt($('#player').css('left')) - 5;
if (nextpos > 0) {
$('#player').css('left', nextpos + 'px');
}
}
$('#right').mousedown(function() {
moveRight(); // Do it now
timer = setInterval(moveRight, 5); // Then every 100 ms
}).mouseup(function() {
clearInterval(timer); // And stop it
});
function moveRight() {
var nextpos = parseInt($('#player').css('left')) + 5;
if (nextpos < PLAYGROUND_WIDTH - 100) {
$("#player").css("left", ""+nextpos+"px");
}
}
// Timer
$(function(){
var timercount = 30;
countdown = setInterval(function(){
$("#timer").html(timercount);
if (timercount <= 0) {
$("#timer").html("TIMES UP");
}
timercount--;
}, 1000);
});
I'm going to assume you're not trying to get a comparison of why you need $(window).load and not $.ready. Anyway, javascript is run as it's seen. You've got jquery looking up elements (#right, #player, etc) that probably haven't been loaded into the page yet. So, because these elements are not on the page, jQuery can't bind these events to them.
Read this through - it may more thoroughly answer your question. http://api.jquery.com/ready/
If you run the code at the end of the page, rather than in the header, those elements should be loaded by the time the javascript runs.
That said, if your code is comparing the size of images, the images need to be loaded first...
You have to put it below your HTML..
<body>
//your html stuff here that uses the script
<script type="text/javascript">
// the js code here
</script>
</body>

Categories