js setTimeOut间隔输出数组内容,使用闭包、迭代、promise、async/await解决异步问题

功能:SetTimeOut每隔一秒输出数组内的内容
首先先定义一个数组

var arr = ["一", "二", "三", "四", "五"];

1:闭包

 // 闭包,for循环遍历数组内容,用闭包的方式挨个输出
    function test() {
        for (var index = 0; index < arr.length; index++) {
            (function (x) {
                setTimeout(function () {
                    console.log(arr[x]);
                }, x * 1000);
            })(index)
        }
    }
    test();

2:迭代

// 迭代,迭代只是循环的一种方式,循环具体有三种for,while,do-while,而迭代指的是循环输出一个列表或者数组的所有元素
// 下面方法只能对数组,要对对象的话Array.prototype.forEach.call
arr.forEach(function (element, i) {
    setTimeout(function () {
        console.log(arr[i])
    }, (i * 1000));
});

3:promise

// promise,使用promise的then来实现每隔一秒输出数组内容
function testPromise(i) {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log(arr[i])
            resolve();
        }, 1000);
    })
}
let num = 0;//循环标志
var testThen = function () {
    if (num < arr.length) {
        testPromise(num).then(
            function (data) {
                num++;
                testThen(num);
            })
    } else {
        console.log("执行完")
    }
}
testThen();

4:async/await

function testAsync(i) {//定义要做的内容
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log(arr[i])
            resolve();
        }, 1000);
    })
}

let num1 = 0;
async function testAwait() {//调用内容时使用async,提醒函数里有异步
    if (num1 < arr.length) {
        await testAsync(num1);//将异步内容用同步方式展示出来
        num1++;
        testAwait(num1);//再次调用,内部循环
    }else{
        console.log("执行完成")
    }
}
testAwait();

就这样吧,头秃,有些地方应该还能再简单点,但是我现在就只能写出这样的,看以后会不会优化一下。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值