嵌套的setTimeout替代? [英] Nested setTimeout alternative?

查看:137
本文介绍了嵌套的setTimeout替代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在1秒钟内执行3个功能。

I need to execute 3 functions in a 1 sec delay.

为简单起见,这些功能是:

for simplicity those functions are :

console.log('1');
console.log('2');
console.log('3');

我可以这样做:(非常难看)

I could do this: ( very ugly)

 console.log('1')
 setTimeout(function () {
     setTimeout(function () {
         console.log('2')
         setTimeout(function () {
             console.log('3')

         }, 1000)
     }, 1000)

 }, 1000)

或者我可以创建数组的函数,并使用 setInterval 全球计数器。

Or I could create an array of functions and use setInterval with global counter.

有没有优雅的方式吗?

(ps函数2不依赖于函数编号1 ...因此 - 每秒执行下一个函数。)。

(p.s. function no.2 is not dependent on function number 1... hence - every sec execute the next function.).

推荐答案

你可以使用 setTimeout 这样的东西:

You can use something like this with setTimeout:

var funcs = [func1, func2, func3],
    i = 0;

function callFuncs() {
    funcs[i++]();
    if (i < funcs.length) setTimeout(callFuncs, 1000);
}
setTimeout(callFuncs, 1000); //delay start 1 sec.

或者直接调用callFuncs()开始。

or start by just calling callFuncs() directly.

更新

setInterval 方法(请注意风险call stacking):

An setInterval approach (be aware of the risk of call stacking):

var funcs = [func1, func2, func3],
    i = 0,
    timer = setInterval(callFuncs, 1000);

function callFuncs() {
    funcs[i++]();
    if (i === funcs.length) clearInterval(timer);
}

这篇关于嵌套的setTimeout替代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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