Last active
January 3, 2021 06:35
-
-
Save okabe-yuya/603cb6d61ebc4dbd208a25ab3b5579f2 to your computer and use it in GitHub Desktop.
await interval function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const interval = async (ms, callback, continueCond) => { | |
const _interval = async () => { | |
await new Promise(resolve => { | |
setTimeout(resolve, ms); | |
}); | |
if (continueCond()) { | |
callback(); | |
await _interval(); | |
} | |
}; | |
await _interval(); | |
} | |
// example | |
const main = async () => { | |
const intervalMs = 3000; | |
console.log("start!!"); | |
// 3秒毎にカウント | |
let count = 0; | |
const callback = (counter) => { | |
console.log("[Info] count: ", counter); | |
count++; | |
}; | |
const continueCond = (counter) => 10 > counter; | |
await interval( | |
3000, | |
() => callback(count), | |
() => continueCond(count), | |
); | |
console.log("finish!!"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment