如何停止setTimeout循环? [英] How to stop a setTimeout loop?
问题描述
我正在尝试使用图像精灵构建一个加载指示器,我想出了这个功能
I'm trying to build a loading indicator with a image sprite and I came up with this function
function setBgPosition() {
var c = 0;
var numbers = [0, -120, -240, -360, -480, -600, -720];
function run() {
Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
if (c<numbers.length)
{
setTimeout(run, 200);
}else
{
setBgPosition();
}
}
setTimeout(run, 200);
}
所以出来看起来像这样
我不得不使用setBgPosition();在其他的内部保持这个循环运行,所以现在我的问题是如何停止这个循环一旦我想[加载完成]?
I had to use setBgPosition(); inside else to keep this running in a loop so now my problem is how to stop this loop once I want [load finished]?
推荐答案
p> setTimeout
返回一个定时器句柄,您可以使用它来停止超时, clearTimeout
。
setTimeout
returns a timer handle, which you can use to stop the timeout with clearTimeout
.
所以例如:
function setBgPosition() {
var c = 0,
timer = 0;
var numbers = [0, -120, -240, -360, -480, -600, -720];
function run() {
Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
if (c >= numbers.length) {
c = 0;
}
timer = setTimeout(run, 200);
}
timer = setTimeout(run, 200);
return stop;
function stop() {
if (timer) {
clearTimeout(timer);
timer = 0;
}
}
所以你可以使用它作为:
So you'd use that as:
var stop = setBgPosition();
// ...later, when you're ready to stop...
stop();
请注意,不要将 setBgPosition
调用本身再次,我刚刚设置了 c
返回到 0
。否则,这不行。另请注意,我已经使用 0
作为超时未挂起的句柄值; 0
不是 setTimeout
中的有效返回值,所以它使一个方便的标志。
Note that rather than having setBgPosition
call itself again, I've just had it set c
back to 0
. Otherwise, this wouldn't work. Also note that I've used 0
as a handle value for when the timeout isn't pending; 0
isn't a valid return value from setTimeout
so it makes a handy flag.
这也是我认为你最好用 setInterval
而不是 setTimeout
。 setInterval
重复。所以:
This is also one of the (few) places I think you'd be better off with setInterval
rather than setTimeout
. setInterval
repeats. So:
function setBgPosition() {
var c = 0;
var numbers = [0, -120, -240, -360, -480, -600, -720];
function run() {
Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
if (c >= numbers.length) {
c = 0;
}
}
return setInterval(run, 200);
}
这样使用:
var timer = setBgPosition();
// ...later, when you're ready to stop...
clearInterval(timer);
尽管如此,我想找到一种方法来使 setBgPosition
通过检测到某些完成条件已经得到满足来阻止它们本身。
All of the above notwithstanding, I'd want to find a way to make setBgPosition
stop things itself, by detecting that some completion condition has been satisfied.
这篇关于如何停止setTimeout循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!