Javascript 30 second console count down timer - javascript

I am interested in creating a basic countdown timer in the console of Javascript. My code needs to countdown from 30 and must stop at 0. I have worked through some code but for some reason it is not working. I am a noob at Javascript (First programming language and only been doing 5 weeks). Please help. Below is my code so far.
var i = 30;
function startTimer() {
var countdownTimer = setInterval(function() {
console.log(i);
i = i - 1;
if (i <= 0) {
clearTimeout(countdownTimer);
}
}, 1000);
}
startTimer();
Thanks for the help! :)

You need to clear interval, not timeout since you are using setInterval for your timer:
var i = 30;
function startTimer() {
var countdownTimer = setInterval(function() {
console.log(i);
i = i - 1;
if (i <= 0) {
clearInterval(countdownTimer);
}
}, 1000);
}
startTimer();

Related

SetTimeout. Stop timer

As in this example to stop setTimout?
var i = 1;
var timerId = setTimeout(function tick() {
if (i == 5) clearTimeout(timerId);
i++;
console.log("Tick");
timerId = setTimeout(tick, 2000);
}, 2000);
I know this code you can change and then everything will work, but I wanted to understand why the first example does not work.
var i = 1;
var timerId = setTimeout(function tick() {
console.log('Tick');
if (i < 5) setTimeout(tick, 2000);
i++;
}, 2000);
The first code snippet continues looping because:
You are changing the timerId with every new timeout you set.
You are clearing the timeout that has already finished executing (because it has called the function), and then creating a new one.
You should be using setInterval() instead of setTimeout(), as an interval will keep repeating indefinitely at the specified frequency, whereas a timeout will only execute once after the specified time has elapsed.
The first example isn't working because you're always setting a timeout, no matter the value of i. Add a return statement if i is equal to 5
var i = 1;
var timerId = setTimeout(function tick() {
if (i == 5) {
return;
}
i++;
console.log("Tick");
timerId = setTimeout(tick, 2000);
}, 2000);
It's OK to clearTimeout after the timer expired, but it's not necessary.
and just because of that, your second code snippet is superior to the first one.
and in your first code snippet, you always set the timeout, even if your if condition is met, and you are suppose to return,
i will re-write the function as shown below
var i = 1;
function tick() {
if (i == 5) {
return;
}
i++;
console.log("Tick");
setTimeout(tick, 2000);
}
setTimeout(tick, 2000);
or using interval as
var i = 1;
function tick() {
if (i == 5) {
clearInterval(timerId);
return;
}
i++;
console.log("Tick");
}
var timerId = setInterval(tick, 2000);

How to run a javascript function X seconds?

I am using setInterval to run a Javascript function that generates a new, random integer in a div. the timer starts when I click on the div. I am having problems with stopping it form generating new numbers after five seconds.
Using setTimeout, I hide the div after 5 seconds; that stops random numbers, but I lose the div.
How can I efficiently stop the generating of numbers in the div, and not hide it?
HTML:
<div id="div" onmousedown='F();'>Click here</div>
JS:
function F(){
var div = document.getElementById("div");
setInterval(function(){
var number = Math.floor(Math.random()*28) ;
div.innerHTML = number;
}, 1000);
setTimeout(function(){
div.style.display = 'none';
},5000);
};
Just use a counter to keep track of the number of times the interval has ticked and then use clearInterval to stop it:
var count = 0;
var intervalID = setInterval(function() {
// generate your random number
count++;
if (count === 5) {
clearInterval(intervalID);
}
}, 1000);
Something hastily written, but what you want to do is keep track of your interval handle and then clear it. You can do this with a setTimeout
var forXsecs = function(period, func) {
var handle = setInterval(func, 1000);
setTimeout(function() { clearInterval(handle); }, period * 1000);
}
The timing is not perfect. Matt's answer would also work.
Another option is a slight change on Matt's answer that removes setInterval and just uses timeouts.
var count = 0;
var forXsecs = function(period, func) {
if(count < period) {
func();
count++;
setTimeout(function() {forXsecs(period, func);}, 1000);
} else {
count = 0; //need to reset the count for possible future calls
}
}
If you just want to simply let it run once each second and that 5 times you can do it like this:
HTML:
<div id="5seconds"></div>
JS:
var count= 0;
setInterval(function(){
if(count < 5){
document.getElementById('5seconds').innerHTML = Math.random();
count++
}
},1000);
This will generate a random number each second. until 5 seconds have passed
you should use clearInterval to stop the timer.
To do so, you pass in the id(or handle) of a timer returned from the setInterval function (which creates it).
I recommend clearing the interval timer (using clearInterval) from within the function being executed.
var elm = document.querySelector("div.container");
var cnt = 0;
var timerID;
function generateNumber()
{
cnt += 1;
elm.innerText = cnt;
if (cnt >= 5) {
window.clearInterval(timerID);
}
}
timerID = window.setInterval(generateNumber, 1000);
.container {display:block; min-width:5em;line-height:5em;min-height:5em;background-color:whitesmoke;border:0.1em outset whitesmoke;}
<label>1s Interval over 5s</label>
<div class="container"></div>

Number counter issue

I have been searching the entire day for a solution to this problem. I like this Counter I found on StackOverflow, but because I am inexperienced using JavaScript, I am not entirely sure how to stop it.
I figured out how to set the value and when to start counting etc, but now I want to add a maximum value. IE: If the counter reaches 20 million, then stop.
I tried the following, but it doesn't work:
var simplicity = formatMoney(20000000);
if (amount.innerText <= simplicity){
function update() {
var current = (new Date().getTime() - start)/1000*0.36+0;
amount.innerText = formatMoney(current);
}
setInterval(update,1000);
}
else{
amount.innerText = simplicity;
}
Try this
var max = 20000000;
var intervalId = setInterval(function () {
var current = (new Date().getTime() - start)/1000*0.36+0;
if (current > max) {
amount.innerText = formatMoney(max);
clearInterval(intervalId);
} else {
amount.innerText = formatMoney(current);
}
}, 1000);
Use clearInterval(id) to stop intervals.

jQuery - End setInterval Loop

I'm running the following.
setInterval(function()
{
update(url, baseName(data));
}
, 1000);
This calls that update function every second.
Is there a way to keep this functionality of calling update every second, but killing it or ending it after 10 seconds?
Have a counter and store the interval reference, then use clearInterval() to end the calls
var counter = 0;
var timer = setInterval(function () {
counter++;
update(url, baseName(data));
if(counter>=10){
clearInterval(timer)
}
}, 1000);
Keep a counter:
var timesCalled = 0;
var t = setInterval(function() {
update(url, baseName(data));
timesCalled++;
if (timesCalled === 10)
clearInterval(t);
}, 1000);
(clearInterval)

setTimeout counter not working

This setTimeout function only runs once and then stops. I get no errors so I have no idea why it's happening.
count = 100;
counter = setTimeout('timer()', 100);
$('#reset').click(function() {
count = 100;
counter = setTimeout('timer()', 100);
})
function timer() {
if (count <= 0) {
clearTimeout(counter);
alert('done');
}
$('#counter').html(count);
count -= 1;
}
I tried a few different formulations of the setTimeout function, including setTimeout(timer(),100) and setTimeout(function() { timer() }, 100)
You should be using setInterval() which repeats a function call, not setTimeout(), which does it once. Also, don't use () in function name reference.
var count = 100;
var counter = setInterval('timer', 100);
$('#reset').click(function() {
count = 100;
counter = setInterval('timer', 100);
})
function timer() {
if (count <= 0) {
clearInterval(counter);
alert('done');
}
$('#counter').html(count);
count -= 1;
}
Yes, that's what setTimeout does. It runs the code once.
You want to use the setInterval method to run the code repeatedly.
setTimeout works correctly but it is not what you are looking for. try setInterval instead. setInteval(function, delay)
setTimeout() - executes a function, once, after waiting a specified number of milliseconds.
You probably would like to go for setInterval() which executes a function, over and over again, at specified time intervals.
Not sure what you're trying to achieve, and I don't understand the $('#reset').click (etc) constructs. Are these JQuery?
However, why not use setInterval()? And then clear the interval timer when your condition is met?
var count = 10;
function counter() {
if ( count > 0 )
{
--count;
var t2 = setTimeout( counter, 1000 );
document.querySelector("#demo").innerHTML = count;
}
else
{
clearTimeout(t2);
document.querySelector("#demo").innerHTML = "Done";
}
}
var countdown_timeout = counter();
<p>Count: <b><span id="demo"></span></b></p>

Categories