setTimeout doesn't run synchronously

廉价感情. 提交于 2019-12-31 04:39:06

问题


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. How to make setTimeout wait to finish before starting a new one?

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);

回答1:


it's an async callback, call the next setTimeout from within the callback of the first.

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);


来源:https://stackoverflow.com/questions/16629072/settimeout-doesnt-run-synchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!