2011-12-23 13 views
0

これはなぜ動作しないのですか?jQuery each with SetTimeout

jeMarkersはGoogleマップマーカーの配列です。

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++; 
    }); 
} 

私はsetTimeout関数せずに同じことをしている場合、それは動作しますが、明らかに、一度にすべてのマーカーを行います。

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

'$(" element ")。each()'の代わりに '$ .each'でsetTimeoutを試してみてください。 – Purag

答えて

2

あなたがsetTimeoutメソッドのコンテキストので、関数内thisオブジェクトをキャッシュする必要があります

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++; 
    }); 
} 
+2

これはクロージャと呼ばれます(*: "JavaScriptは' var 'の周りにクロージャを作成します*)。JavaScriptの最も有用な機能の1つです。クロージャに関する詳細:https://developer.mozilla.org/ja/JavaScript/Guide/Closures – PPvG

+0

PPvGが正しいです、私は明示的に言及しておくべきです:) – mfeineis

+0

それです!私はすべての私の試みで同様のことをやったと確信していますが、私は明らかにそれを正しくしませんでした。どうもありがとう!! – Brigante