js每隔一秒打印1,2,3,4,5
Sunny-117 opened this issue · comments
js每隔一秒打印1,2,3,4,5
function delay(i) {
return new Promise((res) => {
setTimeout(() => {
console.log(i);
res();
}, 1000);
});
}
async function tim() {
for (let i = 1; i < 6; i++) {
await delay(i);
}
}
tim()
for(let i=1;i<6;i++){
setTimeout(() => {
console.log(i)
},i*1000)
}
function delayLog(str) {
return new Promise((resolve, _) => {
setTimeout(() => {
console.log(str);
resolve()
}, 1000);
})
}
async function time() {
for (let i = 1; i <= 5; i++) {
await delayLog(i)
}
}
time();
function print(x) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(x);
resolve();
}, 1000)
})
}
function solve() {
print(1)
.then(() => {
return print(2)
})
.then(() => {
return print(3)
})
.then(() => {
return print(4)
})
.then(() => {
return print(5)
})
}
solve();
function delay(i) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(i);
resolve();
}, 1000);
});
}
async function generate() {
for (let i = 1; i <= 5; i++) {
await delay(i);
}
}
generate();
let 块级作用域
for (let i = 1; i <= 5; i++){
setTimeout(()=>console.log(i),i*1000)
}
var+闭包
setTimeout传参
for (var i = 1; i <= 5; i++){
setTimeout((i)=>console.log(i),i*1000,i)
}
闭包传参
for (var i = 1; i <= 5; i++){
((j)=>setTimeout(()=>console.log(j),j*1000))(i)
}
Promise
const delayPrint = (delay, ...args) => {
return new Promise((res, rej) => {
setTimeout(() => {
console.log(...args)
res()
},delay)
})
}
(async () => {
for (let i = 1; i <= 5; i++){
await delayPrint(1000,i)
}
})()
let a=1 let x = setInterval(()=>{ console.log(a++) if(a===6){ clearInterval(x) x = null } },1000)
function intervalPrint() {
let count = 0
var interval = setInterval(function () {
count++
if (count === 5) {
clearInterval(interval)
}
console.log(count)
}, 1000)
return interval
}
intervalPrint()
// promise
function intervalPrintPromise() {
return new Promise(resolve => setTimeout(resolve, 1000))
}
async function print() {
for (let number = 1; number <= 5; number++) {
await intervalPrintPromise(number).then(() => console.log(number))
}
}
print()