Nested setTimeout alternative?

前端 未结 6 1585
逝去的感伤
逝去的感伤 2020-12-10 04:22

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


        
6条回答
  •  一个人的身影
    2020-12-10 04:40

    There are here two methods. One with setTimeout and anotherone with setInterval. The first one is better in my opinion.

    for(var i = 1; i++; i<=3) {
      setTimeout(function() {
          console.log(i);
        }, 1000*i);
    }
    // second choice:
    var i = 0;
    var nt = setInterval(function() {
          if(i == 0) return i++;
          console.log(i++);
          if(i>=3) clearInterval(nt);
        }, 1000);

提交回复
热议问题