javascriptのよく使うスニペット集
寝る
通常版
code:sleep.js
function sleep(delay) {
return new Promise((resolve, reject) => {
setTimeout(resolve, delay);
});
}
code:sleep.ts
function sleep(delay: number): Promise<void> {
return new Promise((resolve, reject) => {
setTimeout(resolve, delay);
});
}
使い方
code:使い方.js
sleep(500).then(()=>{
//500ミリ秒待ったあとの処理
});
//500ミリ秒待ってる間の処理
code:sleep_ac.js
function sleep(delay, signal) {
return new Promise((resolve, reject) => {
const timeout = setTimeout(resolve, delay);
if (typeof signal != "undefined") {
signal.addEventListener("abort", () => {
clearTimeout(timeout);
reject("aborted");
}, { once: true });
}
});
}
// 使用例
const ac = new AbortController();
sleep(500, ac.signal);
// 止める時
ac.abort();
code:sleep_ac.ts
function sleep(delay: number, signal?: AbortSignal) {
return new Promise((resolve, reject) => {
const timeout = setTimeout(resolve, delay);
if (typeof signal != "undefined") {
signal.addEventListener("abort", () => {
clearTimeout(timeout);
reject("aborted");
}, { once: true });
}
});
}
// 使用例
const ac = new AbortController();
sleep(500, ac.signal);
// 止める時
ac.abort();
もうちょっとマシな使用例
code:fetch_timeout.ts
const fetch_ac = new AbortController();
const timeout_ac = new AbortController();
Promise.race([
sleep(500, timeout_ac.signal).then(() => {
fetch_ac.abort("タイムアウト");
return Promise.reject("タイムアウト");
}),
(res) => {
timeout_ac.abort("fetchが完了しました");
return res;
},
),
]).then((res) => {
console.log(res);
}).catch((rea) => {
console.error(rea);
});
いちいち自分で書かずに済んで便利takker.icon