variable incrementer in setInterval function

这一生的挚爱 提交于 2019-12-24 14:17:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!