功能: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();
就这样吧,头秃,有些地方应该还能再简单点,但是我现在就只能写出这样的,看以后会不会优化一下。