javascript 如何使用js代码间隔一秒打印1,2,3,4,5呢?


摘要:
下文讲述js的间隔1秒输出1,2,3,4,5的方法分享,如下所示:

//1.自执行函数

    for (var i=0; i<5; i++) {
      (function (i) {
        setTimeout(() => console.log(i), 1000*i)
      })(i)
    }

//2. es6块级作用域let

 for (let i=0; i<5; i++) {
      (function () {
        setTimeout(() => console.log(i), 1000*i)
      })()
    }


 var out = (i) => {
      setTimeout (() => console.log(i), 1000*i)
    }
    for (var i=0; i<5; i++) {
      out(i)
    }
 


// Promise.all()方法

    var arr = []
    var output = (i) => new Promise(res => {
      setTimeout(()=>{
        console.log(i)
        res()
      }, 1000*i)
    })
    for (var i=0; i<5; i++) {
      arr.push(output(i))
    }
    Promise.all(arr).then(()=> console.log(5))
 
// async await方法

    var sleep = () => new Promise (res => setTimeout(res, 1000))
    (async function () {
      for (let i=0; i<5; i++) {
        await sleep()
        console.log(i)
      }
    })()