2016-07-10 4 views
1

0.08333秒の時間内に24枚の画像が表示されるはずです。ただし、最後の画像しか表示されません。 HTML:JavaScriptで0.08秒以内に異なる画像を表示する

<!DOCTYPE html><html><head> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script><script type="text/javascript" src="script.js"></script><title>page</title></head><body> 
<img src="untitled.0001.jpg"> 
</body></html> 

$(document).ready(function() { 
$(document).keydown(function(e) { 
    switch(e.which) { 
     case 39: // right 
      for (var i = 1; i != 24; i++) { 
       setTimeout(function(){ 
         $("img").replaceWith("<img src='image.000"+ i +".jpg'>"); 
       },83); 
      } 
      break; 
     default: return; // exit this handler for other keys 
    } 
    e.preventDefault(); // prevent the default action (scroll/move caret) 
}); 
}); 

は、どのように私はそれが0.08333秒

更新のタイムアウト時間内にすべての画像を表示することができます:私はそれを解決しようと、この思い付きました:

$(document).ready(function() { 
$(document).keydown(function(e) { 
    switch(e.which) { 
     case 39: // right 
     var count = 1; 
      while (count!=24) { 
       var waiting = 83 * count; 
       setTimeout(function() {$("img").replaceWith("<img src='avatar/walk/HumanWalk.000"+ count +".jpg'>");}, waiting); 
       count+=1; 
      } 
      break; 
     default: return; // exit this handler for other keys 
    } 
    e.preventDefault(); // prevent the default action (scroll/move caret) 
}); 
}); 

なぜそれはまだ動作していないとだけ最後の画像を示しますか?

+3

可能な重複(http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – JJJ

+0

画像を読み込むのに時間がかかることにも注意してください。表示する前に画像をプリロードすることができます。 –

+0

forループが数ミリ秒以内に終了することに注意する必要があります。つまり、すべてのsetTimeout関数は、forループの開始と終了の間の小さな間隔内で起動されます。それらは連続していません。 – 1sloc

答えて

0

$(document).ready(function() { 

    $(document).keydown(function(e) { 
     switch (e.which) { 
      case 39: // right 
       for (var i = 1; i != 24; i++) { 
        (function(x) { 
         setTimeout(function() { 
          $("img").replaceWith("<img src='image.000" + x + ".jpg'>"); 
         }, i*83); 
        })(i); 
       } 
       break; 
      default: 
       return; // exit this handler for other keys 
     } 
     e.preventDefault(); // prevent the default action (scroll/move caret) 
    }); 
}); 
+0

引数 'i'を追加する必要があります。また、間隔を「83 * i」に固定する –

+0

最後の画像のみを表示します.. –

+0

コードを修正しました。 今すぐお試しください – Roysh

0

このような場合に使用setIntervalこのコードを試してください:

[ループ内のJavaScriptのクロージャ - 単純な実施例]の
$(document).keydown(function(e) { 
    switch (e.which) { 
    case 39: 
     var c = 0; 
     var interval = setInterval(function() { 
     // set the source of your image to 
     // 'image.000' + (c++ -1) + '.jpg' 
     }, 83); 
     if (c === 24) clearInterval(interval); 
    } 
}); 
関連する問題