javascript - 停止 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>
解决方案
正如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;
}
}
所以现在循环基本上会不断重复,没有数字限制,直到满足条件。
推荐阅读
- c - C链表不能在开头添加元素
- java - Spinner Can't Save Selected Value
- objective-c - 封装和生成另一个应用程序并注入参数
- python - 如何在python中存储for循环的所有迭代
- git - Git 推送到远程存储库给出致命错误 SSH HTTPS
- php - 教义:在实体断言错误消息中使用常量
- python - 合并熊猫数据框使用太多内存
- python - 是否可以在 Python 中将列表添加到打印语句?
- python - 在 matplotlib 中设置时间序列的 xlim
- .net-core - 未找到名为“Bearer”的 AuthorizationPolicy