简体   繁体   English

setTimeout不会同步运行

[英]setTimeout doesn't run synchronously

I'm trying to make a function to show some messages after 2 seconds in a 'for' function, but seems like isn't running in order at all, if I set one time higher, it will not wait until is done and just get to the next task. 我试图在'for'函数中创建一个函数来在2秒后显示一些消息,但似乎根本没有按顺序运行,如果我设置一次更高,它将不会等到完成并且只是进入下一个任务。 How to make setTimeout wait to finish before starting a new one? 如何使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);

it's an async callback, call the next setTimeout from within the callback of the first. 它是一个异步回调,从第一个回调中调用下一个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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM