javascript - setTimeout is not waiting before changing the DOM -
i'm trying change classes after specific time settimeout, instant change without waiting 2 seconds wanted. i'm doing wrong?
here js
function addelements() { var data = ["empty","typea","typeb","typec"]; for(var k=0;k<data.length;k++) { var set=document.getelementbyid("empty"); set.setattribute("id", "empty"+k); if(data[k] !== "empty") { var s = set.setattribute("class", data[k]); settimeout(function() { s; }, 2000); } else set.setattribute("class", data[k]); } }
and html
<a href="#" onclick="addelements()">start</a> <div id="empty" class="empty"></div> <div id="empty" class="empty"></div> <div id="empty" class="empty"></div> <div id="empty" class="empty"></div>
corrected js in case need mistake
function addelements() { var time = 0; var data = ["empty","typea","typeb","typec"]; for(var k=0;k<data.length;k++) { var set=document.getelementbyid("empty"); set.setattribute("id", "empty"+k); var cname = data[k]; if(cname !== "empty") { time += 2000; (function(set, cname ) { settimeout(function() { set.setattribute("class", cname ); }, time); })(set, cname); } } }
this 1 way around scoping issue k
var cname = data[k]; if(cname !== "empty") { (function(set, cname ) { settimeout(function() { set.setattribute("class", cname ); }, 2000); })(set, cname); }
Comments
Post a Comment