[英]How to stop the following setInterval() in jQuery
The code below moves an image from top of the screen to the bottom. 下面的代码将图像从屏幕顶部移到底部。 I want this
setInterval()
function to stop once y==-100
but I'm not sure how... 我希望这个
setInterval()
函数一旦y==-100
停止,但是我不确定如何...
var image = $('.background');
var y = 0;
setInterval(function() {
if (y == -100) {
//don't know what to add here
}
image.css('background-position', '0 ' + y + 'px');
y--;
}, 100);
I think I need to use clearInterval
but I don't know what to return. 我想我需要使用
clearInterval
但我不知道要返回什么。
You need to store the return value from setInterval
, which you can then pass to clearInterval
. 您需要存储
setInterval
的返回值,然后可以将其传递给clearInterval
。 The returned value is an opaque reference to the interval, so you shouldn't use it for anything else. 返回的值是对间隔的不透明引用,因此您不应将其用于其他任何用途。
var image = $('.background');
var y=0;
var interval = setInterval(function(){
if(y == -100) {
clearInterval(interval);
}
image.css('background-position', '0 ' + y + 'px');
y--;
}, 100);
You can store the interval's id when calling setInterval
and then invoke clearInterval
with that specific interval's id: 您可以在调用
setInterval
时存储间隔的ID,然后使用该特定间隔的ID调用clearInterval
:
var image = $('.background'); var y = 0; var intervalId = setInterval(function() { if (y === -100) { clearInterval(intervalId); } image.css('background-position', '0 ' + y + 'px'); y--; }, 100);
.background { background-image: url('//placehold.it/200'); width: 200px; height: 200px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="background"></div>
You can do this: 你可以这样做:
var image = $('.background');
var y=0;
var interval = setInterval(function(){
if(y == -100) {
clearInterval(interval);
}
image.css('background-position', '0 ' + y + 'px');
y--;
}, 100);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.