How do I loop this function? - javascript

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>

Related

For loop with a timeout doesn't seem to work and gives weird numbers

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)

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>

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)

Use Variable as Time in setInterval / setTimeout [duplicate]

This question already has answers here:
Changing the interval of SetInterval while it's running
(17 answers)
Closed 9 years ago.
Here is an example situation.
var count,
time = 1000;
setInterval(function(){
count += 1;
}, time);
The code above will add 1 to the "count" var, very 1000 milliseconds.
It seems that setInterval, when triggered, will use the time it sees on execution.
If that value is later updated it will not take this into account and will continue to fire with the initial time that was set.
How can I dynamically change the time for this Method?
Use setTimeout instead with a callback and a variable instead of number.
function timeout() {
setTimeout(function () {
count += 1;
console.log(count);
timeout();
}, time);
};
timeout();
Demo here
Shorter version would be:
function periodicall() {
count++;
setTimeout(periodicall, time);
};
periodicall();
Try:
var count,
time = 1000,
intId;
function invoke(){
intId = setInterval(function(){
count += 1;
if(...) // now i need to change my time
{
time = 2000; //some new value
intId = window.clearInterval(intId);
invoke();
}
}, time);
}
invoke();
You cannot change the interval dynamically because it is set once and then you dont rerun the setInterval code again. So what you can do it to clear the interval and again set it to run. You can also use setTimeout with similar logic, but using setTimeout you need to register a timeout everytime and you don't need to possibly use clearTimeout unless you want to abort in between. If you are changing time everytime then setTimeout makes more sense.
var count,
time = 1000;
function invoke() {
count += 1;
time += 1000; //some new value
console.log('displ');
window.setTimeout(invoke, time);
}
window.setTimeout(invoke, time);
You cant (as far as i know) change the interval dynamically. I would suggesst to do this with callbacks:
var _time = 1000,
_out,
_count = 0,
yourfunc = function() {
count++;
if (count > 10) {
// stop
clearTimeout(_out); // optional
}
else {
// your code
_time = 1000 + count; // for instance
_out = setTimeout(function() {
yourfunc();
}, _time);
}
};
integers are not passed by reference in JavaScript meaning there is no way to change the interval by changing your variable.
Simply cancel the setInterval and restart it again with the new time.
Example can be found here:
http://jsfiddle.net/Elak/yUxmw/2/
var Interval;
(function () {
var createInterval = function (callback, time) {
return setInterval(callback, time);
}
Interval = function (callback, time) {
this.callback = callback;
this.interval = createInterval(callback, time);
};
Interval.prototype.updateTimer = function (time) {
clearInterval(this.interval);
createInterval(this.callback, time);
};
})();
$(document).ready(function () {
var inter = new Interval(function () {
$("#out").append("<li>" + new Date().toString() + "</li>");
}, 1000);
setTimeout(function () {
inter.updateTimer(500);
}, 2000);
});

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