我想在JavaScript中的另一个函数中停止函数循环。这是我试过的代码:
<a onmousedown="startLoop();" onmouseup="stopLoop();" >
Start loop
</a>
<script>
var static loop = 1;
function startLoop() {
while(loop ==1) {
}
alert("stop"); //This line is not executed
}
function stopLoop() {
loop = 2;
}
</script>
这是小提琴: http://jsfiddle.net/A5h8k/4/
答案 0 :(得分:4)
此var static loop = 1;
无效,var loop = 1;
,但您开始无限循环,因此您将无法以此方式停止。
使用setInterval代替
var int = self.setInterval(function(){myLoop()},100);
function myLoop() {
//do stuff
}
function stopLoop() {
window.clearInterval(int);
}