我正在 jquery 的无限循环内运行一个函数。我想在按下退出键时退出循环。我做不到。我的循环无限运行。以下是我到目前为止所做的事情:
var playLoop = function(){
var myVar;
var continueLoop = 1;
while(continueLoop === 1){
$(document).on("keyup",function(e){
if(e.key==="Escape"){
continueLoop = 0;
}
myVar = setInterval(addition,1000);
});
}
}
我想停止运行循环内的函数,即当按下“转义”键时最终停止循环。我缺少什么?我该怎么做?
最佳答案
您需要使用.setTimeout
,一旦您识别出按下了退出键,您就可以使用.clearTimeout
取消它。下面的示例有效。
如果您需要其他东西,请告诉我。
// Start your playLoop after document is ready
$(document).ready(function() {
playLoop();
});
function playLoop() {
// Append a dot so you know it's working
$(".dots").append(".");
// Set a new timeout to count down
playLoopCountdown = setTimeout(playLoop, 1000);
}
// Attach escape key cancel
$(document).on("keyup", function(e) {
if (e.key === "Escape") {
// Stop playLoop
clearTimeout(playLoopCountdown);
// Tell user the timeout has been stopped
$(".dots").append("STOPPED");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>You need to click within this iframe for the escape keypress to be registered.</p>
<div class="dots"></div>
关于jquery - 如何在jquery中的while循环中捕获转义键按下事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53895073/