asyncで遅延実行
ある実行のあとに、もう一つ実行させたい、そしてそのまた後に何秒後に実行
みたいなケースのときに活用した。
コード
const test1 = () => {
alert(1);
}
const test2 = () => {
alert(2);
}
//////////////////////
// 表示のタイミング
//////////////////////
async function delay() {
try {
//秒数と、関数を渡す
await wait(1, test1());
await wait(1, test2());
} catch (err) {
console.error(err);
}
}
//////////////////////
// 遅延実行
//////////////////////
const wait = (sec) => {
return new Promise((resolve, reject) => {
setTimeout(resolve, sec * 1000);
});
};
結果
test1()のalertが実行された1秒後に、test2()のalertが表示される
関数を渡すことで色々と応用できたので個人的メモ
async
超便利
もっとうまく書く方法があれば教えてほしい、、、、、