-->

在setInterval函数变量增量(variable incrementer in setInte

2019-10-18 22:18发布

我有很多与函数的问题,我感到困惑与变量的作用域。 我试图用一个回调函数,但我不能得到它。

我有一个功能,以动画的CSS背景。 我需要的功能,当我点击第二次而setInterval的运行不会重新启动自增变量为0。 看到,当你在该时间点或HTML的时间2单击两次,计数器的顺序不成立的顺序。

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>

Answer 1:

您的变量声明为函数中:

function movie(elm,jumpPx,spriteHeight,duration){
    var inc=0;
    ... other code ...
}

因此,每个函数被调用时,它的INC'重置为0。

var inc = 0;
function movie(elm,jumpPx,spriteHeight,duration){
    ... other code ...
}

如果您将它的功能外,它不会不断进行复位



文章来源: variable incrementer in setInterval function