views:

199

answers:

2

I have a trivial little game I wrote in javascript that creates a wave from where you click. I figured out two ways to make the "wave" move across the screen:

  1. by calling jQuery.animate() with increasingly large times. demo
  2. by recursvely calling setTimeout. demo

The problem I have is that I want the behavior of 2 (columns all grow at the same speed with an offset timing) but with the action of 1 (subsequent clicking compounds the "waves" formed).

Right now on the second demo, if you click again before the "wave" is finished, it immediately clears the setTimeouts and starts them all over again. I want to be able to stack them like in the first example.

You can view the source of either of those pages to see the code (methods are getMouseXYUp and getMouseXYDown).

the basic gist of what i am doing in the second demo is found in these two functions:

function getMouseXYUp(e) {
      $("body").die('mousemove');

      h = (document.height - e.pageY + 17);
       left = id-1;
       right = id+1;
      setTimeout("moveleft()", 100);
      setTimeout("moveright()", 100);

      return true
     }

function moveleft(){
     if (left >= 0){
      $("#div"+left).animate({'height': h}, 400);
      left--;
      setTimeout("moveleft()", 50);
     }
    }
A: 

Looking at the code, looks like you have issues with global variables. You would need to pass along left and right in the function calls and not have it in a global scope.

epascarello
+2  A: 

The problem is that you're resetting the variables "left" and "right" as soon as the second mouse click happens. Is this any closer to what you're looking for?

    function getMouseXYUp(e) {
        $("body").die('mousemove');

        var h = (document.height - e.pageY + 17);
        var left = id-1;
        var right = id+1;
        setTimeout(function() { moveleft(left, h); }, 100);
        setTimeout(function() { moveright(right, h); }, 100);

        return true;
    }

    ...

    function moveleft(left, h) {
     if (left >= 0){
      $("#div"+left).animate({'height': h}, 400);
      left--;
      setTimeout(function() { moveleft(left, h); }, 50);
     }
    }

    function moveright(right, h) {
     if (right < divs){
      $("#div"+right).animate({'height': h}, 400);
      right++;
      setTimeout(function () { moveright(right, h); }, 50);
     }
    }
edsoverflow