moonshineOutlaw
moonshineOutlaw

Reputation: 723

setInterval works then hangs browser javascript

I'm wanting to animate an element using setInterval. I've put my code into an object with 2 functions one to initialize and one to animate using setInterval. When I try to run the code the animation works once then causes the browser to hang. The only thing I can think of is an infinite loop being created somewhere however I can't see anywhere in my code that would cause this.

What is causing the browser to crash, how can this be overcome ?

<div id='box' style='position:absolute;height:100px;width:100px;background-color:#44e'>box</div>
<script>
var box = {
init : function(elemId) {
    box.elem = document.getElementById(elemId);
box.timer = setInterval;
    box.tick = 0;

    box.animate();
},
animate: function() {
    if(box.tick < 100) {
        box.elem.style.top = box.tick +'px';
        box.elem.style.left = box.tick +'px';
        box.tick++;
    } else {
        clearInterval(box.timer);
    }
    var timer = setInterval(box.animate, 50)
}
}
box.init('box');
</script>

Upvotes: 0

Views: 1149

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074248

setInterval sets up a function that will be called repeatedly by the browser until you cancel the interval timer. Your code isn't doing that, because the only call to clearInterval is using box.timer, which is never set to a timer handle (the return value from setInterval). So you end up scheduling thousands of calls (a new series every time animate is called) and bringing the browser to its kneeds.

At the very least, this:

var timer = setInterval(box.animate, 50)

should probably be:

box.timer = setInterval(box.animate, 50);

Or you may want setTimeout (which schedules only one call back).

Upvotes: 2

Related Questions