gpt4 book ai didi

javascript - setTimeout 不同步运行

转载 作者:行者123 更新时间:2023-11-30 10:31:32 25 4
gpt4 key购买 nike

我正在尝试在“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);

最佳答案

这是一个异步回调,从第一个回调中调用下一个 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);

关于javascript - setTimeout 不同步运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16629072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com