2014-12-03 52 views
0

我想在循环结束时设置超时并停止某个功能。设置超时代码无法正常工作

这是我在底部设置超时函数的代码。

//Drawing the car turning and changing speed 
function drawCar() { 

var cx = canvas.width/2; 
var cy = canvas.height/2; 

var totalcars = 2; 
var car_distance = 100; 

    for (i = 0; i <= totalcars; i++) { 
      // Get random positions for stars. 
      var x1 = Math.floor(Math.random() * 400); 
      var y1 = Math.floor(Math.random() * 400); 

      if (x1 >= 190 && y1 >= 0) { 
      x1 += (speed1 * mod1) * Math.cos(Math.PI/180 * angle1); 
      y1 += (speed1 * mod1) * Math.sin(Math.PI/180 * angle1); 

      context.save(); 
      context.translate(x1, y1); 
      context.rotate(Math.PI/180 * angle1); 
      context.drawImage(car1, -(car1.width/1), -(car1.height/1)); 
      context.restore(); 
      } 
} 
if (i == totalcars) { 
    return; 
} 
setTimeout(drawCar, 2000); 
} 

回答

0

setTimeout用于指定函数将是开始在未来一定的时间;您所写的内容可确保您的drawCar将始终再次执行(暂停后)。

如果您删除对setTimeout的呼叫,则当循环结束时,您的功能将停止。 (而if最后是毫无意义的:功能将返回任一方式。)

+0

嘿斯科特,我确实设置了时间,但汽车随机闪烁我不想汽车消失,或出现在每个顶部其他,如果你想看到它,我有它在Jsbin上:http://jsbin.com/zewikarojo/5/edit – 2014-12-03 21:50:33

+0

*不要*调用'setTimeout';这只是让汽车吸引*更多*经常。 – 2014-12-03 22:06:49