如何停止循环 - Javascript 100%

时间:2015-03-07 23:19:13

标签: javascript loops

我希望有人可以帮我解决这个问题。我将列出代码,它工作正常,因为它是一个动画。但是,当我在控制台中检查它时,即使它击中了数组中的最后一项,它也不会停止循环。图像本身会停止,但是如果您查看控制台,它会显示它循环。

这是代码,有吧!

	var position_X = ["0px", "-525px", "-1050px", "-1575px", "-2100px", "-2625px", "-3150px", "-3675px", "-4200px", "-4725px", "-5250px", "-5775px", "-6300px", "-6825px", "-7350px"];

	var _lock = document.getElementById('hi');

		// console.log(_lock);
		_lock.style.border = "1px solid black";
		_lock.style.backgroundImage = "url('http://handbagmanufacturing.com/wp-content/CDN/images/lock.png')";

	function lockAnimation(){
			setInterval(function(){
				var _count = position_X.length;
				for(var i = 0; i < _count; i++){
					if(i == _count) break;
			 		_lock.style.backgroundPosition = position_X[i] + " 263px";
			 		console.log("Here is the background positions : " + i + ") " + position_X[i]);
					}
				}
			, 100);	
	}
#hi {
		    width: 525px;
		    height: 263px;
		    background-position-x: "-7875px"
		}
<button onclick="lockAnimation()">Click Me I'm Irish!</button>
	<div id="hi"></div>

1 个答案:

答案 0 :(得分:2)

setInterval更改为setTimeout。这将只运行一次该函数,而不是每100毫秒运行一次。

	var position_X = ["0px", "-525px", "-1050px", "-1575px", "-2100px", "-2625px", "-3150px", "-3675px", "-4200px", "-4725px", "-5250px", "-5775px", "-6300px", "-6825px", "-7350px"];

	var _lock = document.getElementById('hi');

		// console.log(_lock);
		_lock.style.border = "1px solid black";
		_lock.style.backgroundImage = "url('http://handbagmanufacturing.com/wp-content/CDN/images/lock.png')";

	function lockAnimation(){
			setTimeout(function(){
				var _count = position_X.length;
				for(var i = 0; i < _count; i++){
					if(i == _count) break;
			 		_lock.style.backgroundPosition = position_X[i] + " 263px";
			 		console.log("Here is the background positions : " + i + ") " + position_X[i]);
					}
				}
			, 100);	
	}
#hi {
		    width: 525px;
		    height: 263px;
		    background-position-x: "-7875px"
		}
<button onclick="lockAnimation()">Click Me I'm Irish!</button>
	<div id="hi"></div>