1

I am trying to get this fat div on some moving, but it won't! Help!

<script>

do {
 setTimeout(fly(), 10)
  function fly() {
   var i = 0;
      var left = parseInt(document.getElementById("dick").style.left);
   var top = parseInt(document.getElementById("dick").style.top);
   left++;
   top++;
   document.getElementById("dick").style.left = left + "px";
   document.getElementById("dick").style.top = top + "px"; 
 } 
}

while (i = 0);
</script>
<div id="dick" style="position:absolute; top:100px; left:100px; width:100px; height:100px; background-color:#000000;"></div>
JakeTheSnake
  • 2,456
  • 3
  • 14
  • 26

3 Answers3

3

You should use setInterval instead of setTimeout. Also you should give the setInterval your function instead of giving it the result of it being called.

    setInterval(fly, 10);
    function fly() {
      console.log("flying")
        var i = 0;
        var left = parseInt(document.getElementById("dick").style.left);
        var top = parseInt(document.getElementById("dick").style.top);
        left++;
        top++;
        document.getElementById("dick").style.left = left + "px";
        document.getElementById("dick").style.top = top + "px"; 
}   

check this plunkr http://plnkr.co/edit/L3cid26ybpFYITfjUbmP?p=preview

toskv
  • 30,680
  • 7
  • 72
  • 74
1

Because the code is full of logical mistakes.

setInterval(fly, 100);

function fly() {
    var i = 0,
        el = document.getElementById("dick"),
        left = parseInt(el.style.left),
        top = parseInt(el.style.top);

 el.style.left = ++left + "px";
 el.style.top = ++top + "px"; 
}
<div id="dick" style="position:absolute; top:100px; left:100px; width:100px; height:100px; background-color:#000000;"></div>
Vidul
  • 10,128
  • 2
  • 18
  • 20
1

The way it is now, you should see this in the console:

Uncaught TypeError: Cannot read property 'style' of null

First, move your script afterwards the <body> tag;

Then, try coding something like this, instead:

function fly() {
        var left = parseInt(document.getElementById("dick").style.left);
        var top = parseInt(document.getElementById("dick").style.top);
        left++;
        top++;
        document.getElementById("dick").style.left = left + "px";
        document.getElementById("dick").style.top = top + "px";
        //nsole.log(left+" and "+top);
    }

    var T_TIME = 200; // ms
    var intHandler = window.setInterval("fly()", T_TIME);

You better use setInverval() instead of a setTimeout with a loop.

lockedz
  • 219
  • 6
  • 15