Javascript在循环中不能有多个setTimeout函数

时间:2015-09-14 14:33:10

标签: javascript settimeout html5-data

我有这段代码,允许您在定时延迟上设置CSS更改。它工作得很完美,只是它只允许你有一个实例,而我需要它允许很多。它目前只接受循环中的最后一个元素并保持超时功能。有没有办法让这个循环中的所有超时函数都保存并运行?我认为只是每次都重写setTimeout函数而不是一个独特的函数。

注意:我没有收到控制台错误

Javascript(在onload函数中)

  elems = _('[data-timecss]'); //function to return elems via querySelectorAll()
  for (var i=0; i<elems.length; i++) {
     var tempelem = elems[i];
     var c_info = elems[i].dataset.timecss.split(","); //split to get time
     setTimeout(function() {
       var css_e = c_info[1].split(";"); //split to get css properties
       for (var c=0; c<css_e.length; c++) {
         var css_elem = css_e[c].split(":"); //split property and value
         tempelem.style.setProperty(css_elem[0], css_elem[1]); //set value
       }
     }, c_info[0]); //set time
  }

HTML

<div class="block">
  <p data-timecss="2000,color:green;font-weight:bold;">Change to green after 2000ms</p>
  <p data-timecss="5000,display:none;">Hide this block after 5000ms</p>
</div>

无论哪个data-timecss是最后一个,都将正确运行。所以我可以告诉每次超时功能都被覆盖。有没有人对如何制作这些独特的东西有任何想法,但也保持它像我一样充满活力?

1 个答案:

答案 0 :(得分:1)

你需要关闭 - How do JavaScript closures work?

elems = _('[data-timecss]'); //function to return elems via querySelectorAll()
for (var i=0; i<elems.length; i++) {
    (function(i) { // added this
        var tempelem = elems[i];
        var c_info = elems[i].dataset.timecss.split(","); //split to get time
        setTimeout(function() {
            var css_e = c_info[1].split(";"); //split to get css properties
            for (var c=0; c<css_e.length; c++) {
                var css_elem = css_e[c].split(":"); //split property and value
                tempelem.style.setProperty(css_elem[0], css_elem[1]); //set value
            }
        }, c_info[0]); //set time
    }(i)); // added this
}