emscripten-core / emscripten-core/emscripten
Maximum speed of emscripten_set_main_loop() with setTimeout mode.
- Dominant language
- C++
- Stars
- 27.6k
- Forks
- 3.6k
- Avg merge
- 1d 1h
- Merged PRs (30d)
- 105
Description
There is a ralated issue https://github.com/emscripten-core/emscripten/issues/4200 which fixed the fps when there is some time spent inside the main loop function. But it seems not enough.
I've tested on Chrome for a emscripten_set_main_loop with FPS=1000 and my main loop function cost for 4ms, and currently it runs on a 125fps(8ms per frame) . The performance trace is like

Currently the time until next tick is calculated as following:
```
var timeUntilNextTick = Math.max(0, Browser.mainLoop.tickStartTime + value - _emscripten_get_now()) | 0;
setTimeout(Browser.mainLoop.runner, timeUntilNextTick);
```
When the main loop funtion cost 4ms, the timeUntilNextTick will be 0. But it seems that Chrome will force it to be 4ms.
**My suggestion of solution:**
So can we put the Browser.mainLoop.scheduler() before the Browser.mainLoop.runIter(browserIterationFunc) instead of the tickStartTime calculations? Thus we just scheduler the next tick before the task runs to avoid the time spent in main loop function.
I tried it and the trace is like this. The fps become 250(4ms per frame) and it looks to be the max speed.

Related code: https://github.com/emscripten-core/emscripten/blob/main/src/library_browser.js
Contributor guide
Assessment
This issue has not been assessed yet.