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>
Related
I am using Odometer to show an animated counter:
setTimeout(function (){
$('.odometer').html(8567);
}, 1000);
</script>
<script>
window.odometerOptions = {
duration: 3000
};
I would like the counter to start over at the value I've defined in my html (which is 1000) and then count back up to 8567 and repeat indefinitely. I've tried:
$(document).ready(function () {
function loop(){
setTimeout(function (){
$('.odometer').html(8567);},1000,loop);
loop();
});
But it breaks the counter. I'm assuming I can't mix the setTimeout while defining the loop, but don't know what else to try. The 1000 in the setTimeout function is just a coincidence and is the delay to start the function after page load.
If you want to repeatedly call a function over time like this you should use setInterval not setTimeout.
You need to keep track of the current value of the loop, yours right now is setting the counter to 8567 every time.
const start = 1000;
const max = 1010;
var c = start;
var el = document.getElementById('counter');
function counter() {
if (c > max) {
c = start;
}
el.innerHTML = c + "";
c++;
}
counter(); // Optional, can exclude if you want to delay starting the timer
setInterval(counter , 1000)
<div id="counter"></div>
I am trying to make a counter that counts from 10 to 0 using JavaScript with a loop function and setInterval but this does not work for me:
function count() {
var i;
for (i = numbers.textContent; 0 <= i; i--) {
numbers.textContent = i;
}
}
setInterval(count, 1000);
<div id="countDown">10</div>
You are doing a for loop inside setInterval
var numbers = document.getElementById('countDown');
function count() {
var i;
if(numbers.textContent>0)
numbers.textContent=numbers.textContent-1;
else
clearInterval(handle);
/*for(i=numbers.textContent; 0<=i; i--){
console.log(i)
numbers.textContent= i;
}*/
}
var handle= setInterval(count, 1000);
<div id="countDown">10</div>
This should work:
parseInt(numbers.textContent)
And there are many more:
You need a global variable.
You don't need a for loop for this.
Change the condition.
<div id="countDown">10</div>
<script>
var numbers = document.getElementById('countDown');
var interval = setInterval(count, 1000);
function count() {
var count = parseInt(numbers.textContent);
count--;
if (count == 0) {
clearInterval(interval);
}
numbers.textContent = count;
}
</script>
If you want to see it by loops, you can do using setTimeout:
<div id="countDown">10</div>
<script>
var numbers = document.getElementById('countDown');
function count() {
var count = parseInt(numbers.textContent);
count--;
numbers.textContent = count;
}
for (var i = 1; i <= parseInt(numbers.textContent); i++)
setTimeout(count, 1000 * i);
</script>
the first time count is called, the for loop will run till numbers.textContent is 0(and it's so fast that your eyes just missed that change on the page), and the 2nd call, 3rd call is just iterate around 0, nothing is changed.
BTW, after your counting is finished(or maybe you should give it a stop condition, reference to the DOC), you should unregister the interval, cause it never end by default.
I want to make a countdown in javascript, with simple variables, for loop, set timeout.
I get stuck when trying to make a for loop update realtime (every second) right now I get -1 in webpage.
//HTML PART
<p id=timer>0</p>
//JS PART
var timer = 10;
var text = "";
function f() {
for (timer; timer > 0; timer--) {
text += timer + "<br>";
}
timer--;
if( timer > 0 ){
setTimeout( f, 1000 );
}
}
f();
document.getElementById("timer").innerHTML = timer;
Please explain the error and if I'm doing any stupid mistakes
Looks like you want to show timer value from 10 to 0 by changing the value every second. If so, you can do like this:
1. You need to correct your html by putting quotes around timer like this <p id="timer">0</p>
2. You need to remove for loop as I have commented.
3. Move document.getElementById("timer").innerHTML = timer; inside function f().
var timer = 10;
//var text = "";
function f() {
//for (timer; timer > 0; timer--) {
// text += timer + "<br>";
//}
document.getElementById("timer").innerHTML = timer;
timer--;
if (timer >=0) {
setTimeout(f, 1000);
}
}
f();
<p id="timer">0</p>
You can do it like so, I provided comments in code for explanation:
var count = 10;
function timer(targetValue) {
// display first number on screen
document.getElementById("timer").textContent = count;
// decrease count by 1
count--;
// check if timer is still grater than target value
if (count >= targetValue) {
// call timer() function every second to update
setTimeout(timer, 1000, targetValue);
}
}
timer(0);
Counts down from 10 to 0.
Want to count down from 10 to 5? Simply use timer(5)
I'm trying to implement basic 60 sec counter(A p element with idcounter), that is triggered after a button(counter_start()) is pressed.But I want delay of 1 sec between this and make sure this updates in browser window in real-time
<script type="text/javascript">
function counter_start(){
x=0
for(i=0;i<60;i++){
x++;
document.getElementById("counter").innerHTML=x;
}
}
</script>
P.S: There might be other simple methods of implementing a timer.But it's not about timer...actually I'm a student and trying to figure out the architecture and mechanism of this.
EDIT: please post tested versions of the code, as some of em' posted below DO NOT update in real time
Try this Example
Hope it will work for u
JS
for(i = 1; i <= 3; i++)
{
(function(i){
setTimeout(function(){
alert(i);
}, 1000 * i);
}(i));
}
Javascript operates synchronously in the browser.
You need to use setTimeout or setInterval to schedule the for loop's body to be called every second. I'm using setTimeout in the below example for easier "garbage collection"; we will never reschedule the tick to happen after we don't need to update things anymore.
<script type="text/javascript">
var counter = 0;
function counter_tick() {
if(counter < 60) {
counter++;
document.getElementById("counter").innerHTML = counter;
setTimeout(counter_tick, 1000); // Schedule next tick.
}
}
function counter_start() {
counter_tick(); // First update, also schedules next tick to happen.
}
</script>
It sounds like you are looking for a way to pause the current thread, which isn't possible in JavaScript and would probably be a bad idea anyway (the user's browser would lock up while the thread was paused).
A timer is really the way to go with this, otherwise you are fighting the way the language is intended to work.
There is no sleep-function in JS. But you can use window.setTimeout to call a function in given intervals:
function counter_start(){
// get current value
var value = document.getElementById("counter").innerHTML*1;
// leave function if 60 is reached
if(value == 60) {
return;
}
// set the innerHTML to the last value + 1
document.getElementById("counter").innerHTML=value+1;
// call next iteration
window.setTimeout(function(){counter_start()}, 100);
}
counter_start();
JSFiddle-Demo
For-loops run to completion, so you wouldn't usually use one for this.
You just need a timer and a variable to increment:
var maketimer = function(){
var tick = 0,
interval_ms = 1000,
limit = 10,
id;
return {
start: function(){
var timer = this;
console.log('start');
id = setInterval(function(){
if(tick === limit){
timer.stop();
timer.reset();
return;
}
tick += 1;
console.log(tick);
}, interval_ms);
},
stop: function(){
console.log('stop');
clearInterval(id);
},
reset: function(){
console.log('reset');
tick = 0;
}
};
};
var t = maketimer();
t.start();
If you really need to use a for-loop, then you could use a generator function. They're part of the proposed ES6 spec., and you'll need Firefox 26+ to try this out. However the only point of doing this would be to learn about generator functions.
var maketimer = function(){
var interval_ms = 1000,
limit = 10,
id,
loop,
it;
loop = function*(){
var i;
for(i=1; i<=limit; i+=1){
yield i;
}
};
it = loop();
return {
start: function(){
var timer = this;
console.log('start');
id = setInterval(function(){
var tick = it.next();
console.log(tick.value);
if(tick.done){
timer.stop();
timer.reset();
return;
}
}, interval_ms);
},
stop: function(){
console.log('stop');
clearInterval(id);
},
reset: function(){
console.log('reset');
it = loop();
}
};
};
var t = maketimer();
t.start();
Try this::
var x=0;
var myVar;
function myTimer() {
x++;
document.getElementById("counter").innerHTML = x;
if(x==60)
clearInterval(myVar);
}
function counter_start(){
myVar=setInterval(function(){myTimer()},1000);
}
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>