1

我正在尝试创建一个函数以在“for”函数中在 2 秒后显示一些消息,但似乎根本没有按顺序运行,如果我设置得更高,它不会等到完成而只是进入下一个任务。如何让 setTimeout 在开始一个新的之前等待完成?

time += 2000;
(function(set, cName, time) {
    if (cName == "A" || cName == "B") {
        setTimeout(function() {
           text.innerHTML = "somethibng <br />"+text.innerHTML;
           set.setAttribute("class", "type"+cName );        
        }, time);       
     } else {
        setTimeout(function() {
            text.innerHTML = "something else <br />"+text.innerHTML;
                set.setAttribute("class", "type"+cName );                           
            }, time);

        setTimeout(function() { text.innerHTML = "and then another text <br />"+text.innerHTML; }, time);
                }   
})(set, cName, time);
4

1 回答 1

4

这是一个异步回调,从第一个回调中调用下一个 setTimeout。

time += 2000;
(function(set, cName, time) {
    if (cName == "A" || cName == "B") {
        setTimeout(function() {
            text.innerHTML = "somethibng <br />"+text.innerHTML;
            set.setAttribute("class", "type"+cName );        
        }, time);       
     } else {
    setTimeout(function() {
        text.innerHTML = "something else <br />"+text.innerHTML;
            set.setAttribute("class", "type"+cName );                           

        /******* call second setTimeout once the first one finished ***/
        setTimeout(function() { text.innerHTML = "and then another text <br />"+text.innerHTML;      }bind(<pass things to the second timeout if you need>),    time);  
        /**** notice the bind, it's not mandatory (unless you pass vars to the second timeer) **/

        }), time);


            }   
   })(set, cName, time);
于 2013-05-18T21:23:57.640 回答