Search code examples
javascriptdelaysrc

timing javascript and src changes?


ok so i have this javascript to use the arrow keys to send these javascripts when i press arrowkeys. i have a collaborating script that makes the right('img') command move the image but im trying to change the image as it moves with src changes and delays. Help?

<script type="text/javascript">
document.onkeydown = KeyCheck;       
function KeyCheck(event) {

  var spacebar=32
  var KeyID = event.keyCode;
  switch(KeyID) {

      case 39:
        right('img'); 
        document.getElementById('img').src = 'guyr.png';
        setTimeout("right('img'); 
        document.getElementById('img').src = 'runr.png'; 
        setTimeout("right('img'); 
        document.getElementById('img').src = 'guyr.png';",100);",100);
      break;

   }

}
</script>

Solution

  • If you want to do some sort of a game or animation, try to read a little about it, how to structure your game loop, animations and etc.

    But if you are doing just some sort of test try something like this, is not a beautiful code but the idea of an animation should work:

    document.onkeydown = KeyCheck;
    
    function KeyCheck(event) {
    
        var spacebar = 32;
        var KeyID = event.keyCode;
    
        switch (KeyID) {
    
        case 39:
    
            function guy(fn) {
                right('img');
                document.getElementById('img').src = 'guyr.png';
                setTimeout(function() {
                    fn(guy);
                }, 100);
            }
            function run(fn) {
                right('img');
                document.getElementById('img').src = 'runr.png';
                setTimeout(function() {
                    fn(run);
                }, 100);
            }
    
            guy(run);
    
            break;
        }
    
    }
    

    One function calls another, receiving it by parameter, in order to to continue the animation.