-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(timeline): Run in the background
By using a Web Worker we can run our rAF in another thread which can still update the main-thread. #108
- Loading branch information
1 parent
a865ded
commit 763a720
Showing
2 changed files
with
86 additions
and
26 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
let isWorkerPlaying = false | ||
let timeoutId = null | ||
|
||
// playback-loop | ||
const loop = () => { | ||
|
||
// Only trigger the next iteration if the loop is actually started | ||
if (isWorkerPlaying) { | ||
// Inform the main-thread that we are playing | ||
postMessage(isWorkerPlaying) | ||
|
||
timeoutId = setTimeout(() => { | ||
|
||
// Trigger the next iteration of the playback-loop | ||
requestAnimationFrame(loop) | ||
|
||
// Limit the loop to max 60 fps | ||
}, 1000 / 60) | ||
} | ||
|
||
} | ||
|
||
// The main-thread might start or stop the playback-loop | ||
self.addEventListener('message', e => { | ||
const { isPlaying } = e.data | ||
|
||
// Make sure that the loop can't be started or stopped more than once | ||
if (isPlaying === isWorkerPlaying) { | ||
return | ||
} | ||
|
||
isWorkerPlaying = isPlaying | ||
|
||
if (isWorkerPlaying) { | ||
loop() | ||
} else { | ||
clearTimeout(timeoutId) | ||
} | ||
}) |