2012-11-21 56 views
0

我是新来的JavaScript和我试图创建此循环模拟一些骰子卷。当我点击滚动时,没有任何图像被刷新,并且以显示的破碎图像结束。任何人都可以看到我的错误在哪里?Javascript循环更新图像正在返回破碎的图像

function roll(){ 
     for(x=0;x<10;x++){ 
      var die_num1 = Math.ceil(Math.random()*6); 
      for(y=0;y<20;y++){ 
       var picturetype1 = Math.ceil(Math.random()*3); 
       if (picturetype1 == 1){prefix1 = "die-";} 
       if (picturetype1 == 2){prefix1 = "dicet-";} 
       if (picturetype1 == 3){prefix1 = "dices-";} 
       document.getElementById("dice").src='http://localhost/CodeIgniter_2.1.2/dice/' + prefix1 + die_num1 + '.gif'; 
      } 
     } 
    } 

体:

<input type ="button" value = "Roll" onclick="roll()" > 
    <img name="dice" id="dice" src="http://localhost/CodeIgniter_2.1.2/dice/die-1.gif" > 

我用document.write,以确保至少在最终图像我的文件夹中存在,它的作用。我期望在循环过程中看到循环的图像。同样,我没有使用JavaScript的经验,并根据我认为应该看起来的方式将它们放在一起。任何帮助会在这里

+0

的主要原因这不会工作,因为它只是要快。它不考虑图像的加载时间。对于人眼而言,它只能看到循环中的最后一幅图像。 – svenbravo7

+0

谢谢svenbravo。我曾尝试实施的setTimeout()事件,我想这也许是原因,但我没有成功有两种。我将重新创建和更新的问题。 – vizyourdata

回答

0

感谢您让我朝着正确的方向前进。正如迈克尔所说,我已经重新设计了setTimeout,并且它工作得很好。每次迭代只需要1/10秒,没有太大的变化,但是完全不同。

function roll2(){ 
    var timer = setTimeout ("roll2();", 100); 
    i++; 
    if(i >= 15) clearTimeout(timer); 
    var die_num1 = Math.ceil(Math.random()*6); 
    var picturetype1 = Math.ceil(Math.random()*3); 
    if (picturetype1 == 1){prefix1 = "die-";} 
    if (picturetype1 == 2){prefix1 = "dicet-";} 
    if (picturetype1 == 3){prefix1 = "dices-";} 
    if (i <=15) { 
     document.getElementById("dice").src='http://localhost/CodeIgniter_2.1.2/dice/' + prefix1 + die_num1 + '.gif'; 
    } 
    if (i >=15) { 
     document.getElementById("dice").src='http://localhost/CodeIgniter_2.1.2/dice/die-' + die_num1 + '.gif'; 
     i=0; 
    } 

}

0

appreciated.enter代码,我不希望浏览器作为一个事件驱动的环境中,你从你roll()回来之前甚至考虑更新屏幕。您需要熟悉setTimeout并将其作为一系列计时器事件处理。

+0

我结识了。感谢提示迈克尔! – vizyourdata

+0

不客气。 –