Skip to content Skip to sidebar Skip to footer

Javascript Function Variable All Of A Sudden Becomes Undefined?

this is the weirdest thing. My code is below: function menuSwipe(init){ dojo.query('div.fill div.container div.menu div.group ul').forEach(function(item){ dojo.fx.wipeO

Solution 1:

The problem is that the timeout is running after the function has completed, so the parentItem variable has gone out of scope when the timeout runs.

Create a local variable in that scope, so that a closure is created for the timeout function. That way each iteration has it's own variable:

dojo.query('div.category', item.parentNode).forEach(function(parentItem){
  var itemCopy = parentItem;
  window.setTimeout(function(){
    menuOpen(itemCopy, init);
    doGrayscale(itemCopy);
  }, 100);
});

Post a Comment for "Javascript Function Variable All Of A Sudden Becomes Undefined?"