简体   繁体   English

复选框导致无限循环

[英]Checkbox causes infinite loop

So I'm making a program using html en Javascript where the user can click a button and the program will perform a calculation and a checkbox that when checked will perform that same calculation in a loop. 因此,我正在使用html en Javascript编写程序,用户可以单击一个按钮,该程序将执行计算,并选中一个复选框,当选中该复选框时,它将在循环中执行相同的计算。

  <body>
  <button onclick="javascript:calc();"> Calculate</button>
  <form action="">
   <input id="checkbox" type='checkbox' name='auto' value='Auto' /> 
  </form>

   <script>
    var checkbox = document.getElementById('checkbox');
   function calc() {
     do{
    //Calculate stuff
     }while(checkbox.checked);
    }
   </script>

   </body>

Problem is that when I check the checkbox the webpage just freezes because it is stuck in an infinite loop so I can't uncheck the checkbox to stop it. 问题是,当我选中该复选框时,该网页只是冻结,因为它陷入了无限循环,因此我无法取消选中该复选框以将其停止。

Is there any way to stop it from going into an infinite loop? 有什么方法可以阻止它进入无限循环吗?

function calc(){
if(conditionIsTrue){ // do smth here}
else{
//do another stuff here
}
}

There is a way: not to write an infinite loop? 有一种方法:不写无限循环? You are performing the // calculate stuff part over and over (unless you have a break in there) while the checkbox is checked, and since it runs on the ui thread the ui is frozen. 您正在// calculate stuff反复执行// calculate stuff部分(除非在那里有break ),并且选中了该复选框,并且由于它在ui线程上运行,因此ui被冻结。

The moment you check the checkbox, you are putting the code into an infinite loop. 选中复选框后,您会将代码置于无限循环中。 That will freeze up the page and not allow the user to uncheck the box. 这将冻结页面,并且不允许用户取消选中该框。 You can try something with setTimeout like such. 您可以尝试使用setTimeout这样的方法。

const foo = () => {
  if (checkbox.checked) {
    //do math
    setTimeout( () => {
      foo();
    }, 3000)
  }
}

Set the function to fire when the checkbox is clicked, and if it is checked, you can do the calculations and it will recursively call itself again after 3 seconds and check if the checkbox is still checked. 将函数设置为在单击复选框时触发,如果选中该复选框,则可以进行计算,并且它将在3秒后递归调用自身,并检查该复选框是否仍处于选中状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM