0%

delate function js

I make a adjust seat website, which increase my understanding of javascript.

I learned how to delate the loop

1
2
3
4
5
6
7
8
9
10
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function delayedLoop() {
for (let i = 0; i < 10; i++) {
await delay(1000);
console.log(i);
}
}
delayedLoop();

and

1
2
3
4
5
for (let i = 0; i < 10; i++) {
setTimeout(() => {
console.log(i);
}, i * 1000);
}

Once, I make a sleep function, but I forget to return the Promise data.

Which let me impress. And I find that no need to change asyncfunction.

1
2
3
function sleep(ms){
return new Promise(resolve => setTimeout(resolve, ms));
}

Because it is no use to add async to sleep function, only add async to your operative function, adding await sleep(delate) just take effect. Otherwise, your operative wouldn’t wait the sleep function, running next code directly.

請打賞支待一下.