setInterval 函数中的变量增量器 [英] variable incrementer in setInterval function
问题描述
我的函数有很多问题,我对变量作用域感到困惑.我尝试使用回调函数,但无法获取.
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.
我有一个使用 css 为背景设置动画的功能.当我在 setInterval 运行时第二次单击时,我需要该函数不会将 incrementer 变量重新启动为 0.看到当你在html的time1或time2点击两次a时,counter的顺序不持有顺序.
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>
推荐答案
你的变量声明在函数内:
Your variable declaration is within the function:
function movie(elm,jumpPx,spriteHeight,duration){
var inc=0;
... other code ...
}
因此,每次调用该函数时,都会将 'inc' 重置为 0.
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
这篇关于setInterval 函数中的变量增量器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!