首页 > 解决方案 > 停止 forloop 或函数

问题描述

我想要一些关于如何在将 20 个数字绘制到透视 div 后停止 for 循环的建议。我尝试了停止功能/清除间隔,设置超时等。实现这一目标的最佳方法是什么,因为我被困在最好的方法上

enter code here 
  function lottoNumbers()
  {
    var lottoNums = [];

    for(var i=0; i <1 ; i++)
    {
      var temp =Math.floor(Math.random() * 80 + 1);
      if(lottoNums.indexOf(temp) == -1)

      {

        lottoNums.push(temp);
        document.getElementById('square' + temp).innerHTML = lottoNums[i];
                document.getElementById('square0').innerHTML = lottoNums[i];
      }
      else
      {
        i--;
      }
    }
  }

//test resizing div
function alterSize(type) {
 var targetDiv = document.querySelector("#square0");
 targetDiv.classList.add(type);
 setTimeout(function(){
  targetDiv.classList.remove(type);
  }, 2000)
}


/*
onload="setInterval(lottoNumbers, 3000);
*/
  </script>

</head>


<body bgcolor="lightblue" onload="setInterval(start, 3500)" >
  <h1><center>GENERATE LOTTO NUMBERS</center></h1>

标签: javascriptfunctionfor-looplogic

解决方案


正如rocky所说,在这种情况下,while循环更适合使用for循环,而不是使用for循环,尝试使用以下逻辑示例,看看你是怎么做的。

var lottoNumbers = 0;
var lottoNumbersCondition = false;

while(lottoNumbersCondition == false){
//your code and logical proccess goes here..
//and then your conditions will look like this
 if(condition to add lotto number = true){
    lottonumbers++;
 }

 if(lottoNumbers == 20){
    lottoNumbersCondition = true;
 }

}

所以现在循环基本上会不断重复,没有数字限制,直到满足条件。


推荐阅读