0

I am making a weird block movement thing, but after it moved 10 times it says:

Uncaught RangeError: Maximum call stack size exceeded

And my purpose is to let it move the whole time, here is the code BTW:

<html>
    <head>
        <title>Look - The game</title>
    </head>
    <body>
        <div id="square" style="position:absolute; width:5px; height:5px; background:black"></div>
        <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
        <script>
            var square = document.getElementById("square");
            var duration = 1000;
            var steps = 1;
            function movesquare(){
                var randomtop = Math.floor(Math.random() * screen.height);
                var randomleft = Math.floor(Math.random() * screen.width);
                $(square).animate({marginTop:randomtop, marginLeft:randomleft}, duration, movesquare);
                duration -= steps;
                steps = steps * 2;
            }
            movesquare();
        </script>
    </body>

7
  • Is there a reason why you are using recursion? Perhaps this is inadvertent? This is the cause of your stack problems. Commented Dec 7, 2014 at 15:49
  • your are doing something wrong ... ! Commented Dec 7, 2014 at 15:50
  • 3
    Maximum call stack size exceeded indicates that you have an a kind of endless loop and if the browser would not stop your script, your browser most likely will become unresponsive in such a situation. Commented Dec 7, 2014 at 15:50
  • I want to get it moving the whole time, or is there an another way to do that. Here is btw the page Commented Dec 7, 2014 at 15:51
  • 1
    @LeoDeng it's only going to be recursive when duration is less than or equal to zero. So long as it's greater than zero, there'll be no recursion. Commented Dec 7, 2014 at 15:59

1 Answer 1

3

Your problem is that:

$(square).animate({marginTop:randomtop, marginLeft:randomleft}, duration, movesquare);

Will call movesquare immediately when duration is 0 or smaller. At the time this happens you created an endless loop.

You need to make sure that duration does not become 0.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I didn't realised that the duration will became lower than 0 in 10 steps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.