Skip to content

Instantly share code, notes, and snippets.

@kawaz
Last active Mar 11, 2021
Embed
What would you like to do?
タブがバックグラウンドになってもサボらない setInterval
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)}
}
}
@kawaz

This comment has been minimized.

Copy link
Owner Author

@kawaz kawaz commented Mar 11, 2021

↓こんな感じに使う

{
const log = (...args) => console.log(...args)
const {stop} = superInterval(log, 500, 1, {a:2}, [3])
setTimeout(stop, 3000)
}
@kawaz

This comment has been minimized.

Copy link
Owner Author

@kawaz kawaz commented Mar 11, 2021

CSPが設定されているサイトでこれを使う場合は worker-src data: が必要になる。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment