Reputation: 682
As always, I would appreciate very much if somebody out there could help me a little bit with this code.
I have the following lines of code:
var count = 0;
var limit = 2000;
function liveCount(){
var increment = count + 10;
count = increment;
if(count <= limit){
document.getElementById('showCount').textContent=count;
}else{
clearInterval();
}
}
var counter = setInterval('liveCount()', 10);
What this code does is simulate a counter from 0 to X as a chronometer would do.
It works perfect when I use it stand-alone, it starts counting and updates the count in 10 miliseconds intervals until it reaches the limit and then it stops.
So far so good.
My problem is that when I nest this code inside another function, which is the one that will provide the value for the "count and limit" variables, I get an error saying that the "liveCount()" is not defined, refering to the parameter of the "setInterval()".
I have tried everything I can think of and I cant get it to work.
Any ideas what am I missing or doing wrong?
Thank you all.
Upvotes: 1
Views: 489
Reputation: 60414
As you've written it, liveCount
must be a property of the global window
object. Putting this code inside a function defines liveCount
as local to that function, which means that window.liveCount
does not exist.
Don't pass setInterval
code to execute; instead, give it a reference to the function, like this (notice that there are no quotes):
var counter = setInterval(liveCount, 10);
Full example:
function someOtherFunc(limit) {
var count = 0;
function liveCount() {
var increment = count + 10;
count = increment;
if (count <= limit) {
document.getElementById('showCount').textContent = count;
} else{
clearInterval();
}
}
var counter = setInterval(liveCount, 10);
}
You probably also want to return counter
(or something like that), but you don't show enough code to be sure.
Upvotes: 1
Reputation: 785
Maybe this is what you are looking for...
function liveCount(count, limit){
var increment = count + 10;
count = increment;
if(count <= limit){
document.getElementById('showCount').textContent=count;
}else{
clearInterval(counter);
}
}
function wrapper() {
// calculate count and limit
count = 0;
limit = 2000;
liveCount(count, limit);
}
var counter = setInterval(wrapper, 10);
Upvotes: 1
Reputation: 5731
Put what your invoking inside a closure.
var counter = setInterval(function() {
liveCount();
}, 10);
Example: http://jsfiddle.net/MattLo/HATmY/
Upvotes: 0