Last active
December 14, 2023 12:34
-
-
Save kawaz/72f61d8389fed0e9d4e7dc9eb01b39c8 to your computer and use it in GitHub Desktop.
タブがバックグラウンドになってもサボらない setInterval
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 superInterval = (cb, interval=1000, ...args) => { | |
try { | |
const code = `self.addEventListener('message', msg=>{setInterval(()=>self.postMessage(null), msg.data)})` | |
const w = new Worker(`data:text/javascript;base64,${btoa(code)}`) | |
w.onmessage = () => cb(...args) | |
w.postMessage(interval) | |
return {stop:()=>w.terminate()} | |
} catch(_){ | |
// 実装の問題またはCSPによる拒否などで Worker が使えなければ普通の setInterval を使う | |
const id = setInterval(cb, interval, ...args) | |
return {stop:()=>clearInterval(id)} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
CSPが設定されているサイトでこれを使う場合は
worker-src data:
が必要になる。