javascript - setTimeout produces a scope error -


my question simple. i'm using settimeout inside loop, during runtime error produced saying:

uncaught typeerror: cannot call method 'setattribute' of undefined 

my experience javascript slim (i'm skipping jquery sake of learning) , assume has way i'm calling settimeout.

take @ function, know why "elements" not available inside anonymous function.

function hide_visable_elements() {     // remove body eventlistener     var body = document.getelementsbytagname("body");     body[0].removeeventlistener("click", hide_visable_elements, true);      var elements = document.getelementsbyclassname("visible");     (var = 0; < elements.length; ++i)     {     elements[i].removeattribute("class");     settimeout(function() { elements[i].setattribute("class", "hidden") }, 300);     }    } 

here's example of how capture current value of iteration when executed after loop has completed (it always after, because of asynchronous nature), right thing:

function sethidden(element) {     return function() {         element.setattribute("class", "hidden");     }; }  function hide_visable_elements() {     // remove body eventlistener     var body = document.getelementsbytagname("body");     body[0].removeeventlistener("click", hide_visable_elements, true);     var elements = document.getelementsbyclassname("visible");     (var = 0; < elements.length; ++i) {         elements[i].removeattribute("class");         settimeout(sethidden(elements[i]), 300);     } } 


btw i'm using description "long after" relatively, minimal amount of time passes before deferred functions possibly executed 4 or 13 milliseconds loop execution time measured in micro or nano seconds.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -