问题
I have lot of problems with a function and I get confused with the variable scope. I tried with a callback function, but I cannot get it.
I have a function to animate a background with css. I need that function doesn't restart the incrementer variable to 0 when I click for a second time while a setInterval is running. See that when you click a twice in time1 or time2 of html, the order of counter doesn't hold the order.
function movie(elm,jumpPx,spriteHeight,duration){
var inc=0;
var time=setInterval(function(){
if(inc<spriteHeight){
inc+=jumpPx;
//elm.style.backgroundPosition='0px -'+inc+'px';
elm.innerHTML=inc;
}else{
clearInterval(time);
elm.style.backgroundPosition='0px -0px';
}
},duration);
}
<p onclick="movie(this,1,1000,1000)">time1</p>
<p onclick="movie(this,1,1000,1000)">time2</p>
回答1:
Your variable declaration is within the function:
function movie(elm,jumpPx,spriteHeight,duration){
var inc=0;
... other code ...
}
Therefore, each time the function is called, it resets 'inc' to 0.
var inc = 0;
function movie(elm,jumpPx,spriteHeight,duration){
... other code ...
}
If you move it outside the function, it won't keep resetting
来源:https://stackoverflow.com/questions/19785307/variable-incrementer-in-setinterval-function