Les Mac
Les Mac

Reputation: 23

window.setInterval possible scope issue?

Thanks for taking the time to read this post. Finally built up enough courage to ask a question here :) Hope I ask my question in the correct way.

My problem is that I am trying to randomly animate "squares" around a page but am having an issue with the setInterval method.

You can find it here http://jsfiddle.net/xEMXh/

In the Init function I am trying to go though each ghost element and set it a interval function that will then make it animate in a random direction every X seconds.

for (ghostCount = 0; ghostCount < ghosts.length; ghostCount += 1) {
            var speed = LesMccutcheon.GhostHunter.GetSpeed($(ghosts[ghostCount]).attr('data-speed')),
                activeGhost = ghosts[ghostCount];
            window.setInterval(function() {
                LesMccutcheon.GhostHunter.MoveInDirection(activeGhost);
            }, speed);
        }

What is happening is only the last "ghost" element is animating. I know this is because in the for loop I am overriding the variable and by the time the first interval is called activeGhost is the last set in the for loop.

I tried using ghosts[ghostCount] directly in the set.Interval but it seems set interval cannot access this. I tried setting it to a variable inside the set.Interval anom function but it logged as undefined.

My only other half baked idea is to try and set an incremental var identifier but that seems quite counter productive and not a good way to go.

Thanks in advance for any advice!

Les

Upvotes: 0

Views: 133

Answers (1)

bukart
bukart

Reputation: 4906

in your code the variable activeGhost will be overwritten for each loop. just put the calling of setInterval into a closure like this

( function (activeGhost) {
    window.setInterval(function() {
        LesMccutcheon.GhostHunter.MoveInDirection(activeGhost);
    }, speed);
} ( activeGhost) );

this way the reference to the correct element should be kept.

Upvotes: 2

Related Questions