1) 如何让 while 循环在后台运行,并且尽管 while 循环,网页仍能响应用户点击。 如果我启动字符生成while循环,我无法将数据输入到“输入”,因为生成循环占用了所有资源。实际上,每当我单击“开始”时,我都会收到网页没有响应的消息,询问我是否要停止它。选择“停止”后,我看到字符已生成。然而,在输入字段中输入字符并通过“停止”触发器来停止程序是非常困难的,并且通常会导致网页崩溃。
2)如何使多个 jquery while 循环同时运行,此外,网页应该具有响应能力并可供用户访问。
<!DOCTYPE html>
<html>
<head>
<script src="theme/assets/js/jquery/jquery-2.2.3.min.js"></script>
</head>
<body>
<div id="Start"> <b> Start </b> </div>
<div id="Stop"> <b> Stop </b> </div>
<br><br> <div id="random"> </div>
<br><br> <input id="input" type="text" size="500">
<script>
// how to manage without global variables? how to pass variables to the function
var flag = false;
var charstr = "zxcvbnm,\.\/asdfghjkl;\'qwertyuiop[]\\`ąčęėįšųū90\-ž";
var charstrL = charstr.length;
$("#Start").click( function() {
$("#lesson").text("clicked Start");
flag =true;
$(this).val('flag');
while(flag){
setInterval(function() { // this code is executed every 500 milliseconds:
var rand = Math.random();
var num = Math.floor( ( Math.random() * (charstr.length -1) ) );
$("#lesson").text(charstr[num]);
}, 500);
}//while
}); // $("#Start").click( function() {
$("#Stop").click( function(){
flag=false;
$(this).val('flag');
alert('clicked Stop');
});
</script>
</body>
</html>
最佳答案
如果 while
循环正在进行 DOM 操作,则无法在后台运行,因为浏览器 JavaScript 中只有一个主 UI 线程。
您可能也不想这样做,因为这段代码:
while (flag) {
setInterval(function() { // this code is executed every 500 milliseconds:
var rand = Math.random();
var num = Math.floor( ( Math.random() * (charstr.length -1) ) );
$("#lesson").text(charstr[num]);
}, 500);
}
不断添加附加计时器以每 500 毫秒调用该代码。在很短的时间内,您的浏览器将变得完全无响应。
只需设置setInterval
,让里面的代码根据flag
决定是否运行:
setInterval(function() { // this code is executed every 500 milliseconds:
if (flag) {
var rand = Math.random();
var num = Math.floor( ( Math.random() * (charstr.length -1) ) );
$("#lesson").text(charstr[num]);
}
}, 500);
您可以拥有其中的几个,但如果您有很多,您可能会考虑减少数量,并且每次只让它们做不止一件事。
关于javascript - jquery,后台运行的while循环,同时while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37240698/