我创造了一个小游戏,每1秒创建一个敌人,直到有10个敌人(10秒) 如果我没有clearInterval这样做,它会创造整个时间的敌人 所以我想在它达到10时停止
var initEnemy = function ()
{
//enemy div
for(var i = 0; i < 10; i++)
var timerid = null;
function IntervalFunction()
{
var randomX = Math.floor(Math.random() * 190);
var randomY = Math.floor(Math.random() * 50);
enemy.push(new Enemy(randomX, randomY).create());
}
IntervalFunction();
setInterval(IntervalFunction,1000);
clearInterval(IntervalFunction),10000);
}
答案 0 :(得分:0)
clearInterval
没有采取第二个论点。
并且setTimeout更容易包围...一个简单的方法是计算到目前为止你创建了多少敌人,并在达到限制时不运行setTimeout
:
var initEnemies = function () {
var numEnemiesCreated = 0;
function createAnotherEnemy() {
var randomX = Math.floor(Math.random() * 190);
var randomY = Math.floor(Math.random() * 50);
enemy.push(new Enemy(randomX, randomY).create());
numEnemiesCreated += 1;
if (numEnemiesCreated < 10)
setTimeout(createAnotherEnemy, 1000);
}
createAnotherEnemy();
}
还有一个带for循环的版本,它从现在开始调度函数调用0s,1s,2s,...,9s:
var initEnemies = function () {
function createEnemy() {
var randomX = Math.floor(Math.random() * 190);
var randomY = Math.floor(Math.random() * 50);
enemy.push(new Enemy(randomX, randomY).create());
}
for (var i=0; i < 10; i++)
setTimeout(createEnemy, i * 1000);
}
<强>更新强>
此处包含setInterval
和clearInterval
的版本。您仍需要计算到目前为止已创建的敌人数量,并且您必须在clearInterval
调用中使用间隔ID。哈文没有对此进行测试,抱歉!
var initEnemies = function () {
var numEnemiesCreated = 0;
var intervalId;
function createEnemy() {
var randomX = Math.floor(Math.random() * 190);
var randomY = Math.floor(Math.random() * 50);
enemy.push(new Enemy(randomX, randomY).create());
// Unschedule ourselves after 10th run
numEnemiesCreated += 1;
if (numEnemiesCreated == 10)
clearInterval(intervalId);
}
intervalId = setInterval(createEnemy, 1000);
}