[英]JavaScript setTimeout not working with prompt box
這是我的代碼:
var t = setTimeout("increment();", 1000 * 3);
var st;
function increment() {
st = 1;
}
for (i = 0; i < 10; i++) {
cnt = i;
var no1 = Math.floor(Math.random() * 101);
var no2 = Math.floor(Math.random() * 101);
if ((i % 4) == 0) {
crct_ans[i] = no1 + no2;
quest[i] = no1 + " + " + no2;
}
else if ((i % 4) == 1) {
crct_ans[i] = no1 - no2;
quest[i] = no1 + " - " + no2;
}
else if ((i % 4) == 2) {
crct_ans[i] = no1 * no2;
quest[i] = no1 + " x " + no2;
}
else if ((i % 4) == 3) {
crct_ans[i] = no1 / no2;
quest[i] = no1 + " / " + no2;
}
ans[i] = prompt(quest[i], "");
if (st == 1) break;
}
如果3秒鍾過去,我想停止for循環。 但這是行不通的。 For循環還會在3秒后運行。 我怎樣才能做到這一點?
刪除()
和這樣的引號:
var t = setTimeout(increment, 3000);
()
會立即/立即禁用該功能的運行,而setTimeout
需要callabck。 eval
。 順便說一句,優良作法是使用單個var
關鍵字聲明所有變量,如下所示:
var t = setTimeout(increment, 3000), st;
嘗試像這樣格式化:
var t = setTimeout(function(){increment();}, 3000);
如果它符合您的要求,您只需檢查經過了多少時間。
例:
var start = new Date();
for(i = 0; i < 10; i++){
var end = new Date();
var elapsed = end.getTime() - start.getTime();
if (elapsed >= 3000)
break;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.