Brigante
Brigante

Reputation: 1981

jQuery each with SetTimeout

Can anyone tell me why this doesn't work?

jeMarkers is an array of Google Maps markers.

function toggleBounce() {
    var bcounter = 0;
    $(jeMarkers).each(function () {
        setTimeout(function () {
            if (this.getAnimation() != null) {
                this.setAnimation(null);
            } else {
                this.setAnimation(google.maps.Animation.BOUNCE);
            }
        }, bcounter * 100);
        bcounter++;
    });
}

If I do the same without the setTimeout function it works but obviously does all the markers at once:

function toggleBounce() {
    $.each(jeMarkers, function () {
        if (this.getAnimation() != null) {
            this.setAnimation(null);
        } else {
            this.setAnimation(google.maps.Animation.BOUNCE);
        }
    });

Upvotes: 0

Views: 282

Answers (1)

mfeineis
mfeineis

Reputation: 2657

You have to cache the this object inside the function since the context of the setTimeout is not automatically set:

function toggleBounce() {
    var bcounter = 0;
    $(jeMarkers).each(function () {
        var that = this; // <- Cache the item
        setTimeout(function () {
            if (that.getAnimation() != null) {
                that.setAnimation(null); // <- Now we can call stuff on the item
            } else {
                that.setAnimation(google.maps.Animation.BOUNCE);
            }
        }, bcounter * 100);
        bcounter++;
    });
}

Upvotes: 2

Related Questions