js: Switch to window.requestAnimationFrame() for timing

This is an API specifically designed for the purposes of timing
animations.  Unlike setInterval, it tries to synchronise with the screen
refresh rate.  It naturally passes us timing information, saving the
need to construct a Date object every frame.  It has the nice feature
that browsers (at least Firefox 91) will call it less frequently when
the puzzle page isn't visible, which saves CPU time in puzzles that run
a timer continuously.
This commit is contained in:
Ben Harris
2022-10-26 10:05:04 +01:00
parent c5a2446fae
commit 7982002a64
2 changed files with 23 additions and 15 deletions

View File

@ -194,29 +194,37 @@ mergeInto(LibraryManager.library, {
/* /*
* void js_activate_timer(); * void js_activate_timer();
* *
* Start calling the C timer_callback() function every 20ms. * Start calling the C timer_callback() function every frame.
*/ */
js_activate_timer: function() { js_activate_timer: function() {
if (timer === null) { if (!timer_active) {
timer_reference_date = (new Date()).valueOf(); timer_reference = performance.now();
timer = setInterval(function() { var frame = function(now) {
var now = (new Date()).valueOf(); current_timer = null;
timer_callback((now - timer_reference_date) / 1000.0); timer_callback((now - timer_reference) / 1000.0);
timer_reference_date = now; /* The callback may have deactivated the timer. */
return true; if (timer_active) {
}, 20); timer_reference = now;
current_timer = window.requestAnimationFrame(frame);
}
}
timer_active = true;
current_timer = window.requestAnimationFrame(frame);
} }
}, },
/* /*
* void js_deactivate_timer(); * void js_deactivate_timer();
* *
* Stop calling the C timer_callback() function every 20ms. * Stop calling the C timer_callback() function every frame.
*/ */
js_deactivate_timer: function() { js_deactivate_timer: function() {
if (timer !== null) { if (timer_active) {
clearInterval(timer); timer_active = false;
timer = null; if (current_timer !== null) {
window.cancelAnimationFrame(current_timer);
current_timer = null;
}
} }
}, },

View File

@ -90,8 +90,8 @@ var midpoint_test_str = "ABCDEFGHIKLMNOPRSTUVWXYZ0123456789";
var midpoint_cache = []; var midpoint_cache = [];
// Variables used by js_activate_timer() and js_deactivate_timer(). // Variables used by js_activate_timer() and js_deactivate_timer().
var timer = null; var timer_active = false;
var timer_reference_date; var timer_reference;
// void timer_callback(double tplus); // void timer_callback(double tplus);
// //