user3168806 user3168806 - 7 months ago 19
Javascript Question

Moving an image up the screen using do and while loops

I am learning JavaScript and have been developing a simple game that is essentially a balloon that you can move around on the screen. I managed to do keypresses etc with a lot of help and the balloon moved about just perfectly.

I now want to simulate gravity, by having the balloon move one pixel down the screen if the balloon image was above a value, i tried to do this with the following do while statement:

var balloon = document.getElementById("balloon");
var bottom = parseInt (balloon.style.bottom, 10);

do {
balloon.style.bottom = bottom + 50 + 'px';
}
while (bottom = bottom > 600) // Gravity


What I want this to do, is to check the code is working by making the balloon move up the page 1 pixel if the bottom value is less than 600.

I have stripped out all the code I used to make the balloon move.

If I could just see the balloon move slowly up the page I would be very happy, because then at least I know I can just switch the values round when I've added the movement back in.

9lo 9lo
Answer

The other answers address the issue of attempting an animation with an explicit loop. As they have pointed out, you should use timers.

Because it seemed like fun, I made you a simple example of how to use a timer to animate a balloon falling: http://jsfiddle.net/dmuu9w97/

The key code is the following:

// Make balloon fall 1px every 10ms
setInterval(function() {
    var bottom = getBalloonBottom();
    if (bottom > 0)
        balloon.style.bottom = bottom - 1 + "px";
}, 10);