setTimeout不会同步运行 [英] setTimeout doesn't run synchronously

查看:136
本文介绍了setTimeout不会同步运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

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

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

这篇关于setTimeout不会同步运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆