我试图在'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);
答案 0 :(得分: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);