From 523e46bb1d6f4f260c610a270e591bdc0202553f Mon Sep 17 00:00:00 2001 From: "Mario T. Lanza" Date: Wed, 15 May 2024 16:41:06 -0400 Subject: [PATCH] improved tick precision --- src/reactives/types/observable/concrete.js | 28 +++++++++++++++++----- 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/src/reactives/types/observable/concrete.js b/src/reactives/types/observable/concrete.js index a0fa791b..4370fda0 100644 --- a/src/reactives/types/observable/concrete.js +++ b/src/reactives/types/observable/concrete.js @@ -165,18 +165,34 @@ function time(){ return _.date().getTime(); } -function tick2(interval, f){ +function tick3(interval, frame = 0, f = time){ return observable(function(observer){ - const iv = setInterval(function(){ - pub(observer, f()); - }, interval); + const seed = performance.now(); + const target = seed + frame * interval; + const self = {seed, target, frame, stopped: false}; + function callback(){ + self.offage = performance.now() - self.target; + if (self.offage >= 0) { + pub(observer, f(self)); + self.frame += 1; + self.target = self.seed + self.frame * interval; + } + const delay = Math.abs(Math.round(Math.min(0, self.offage), 0)); + self.stopped || setTimeout(callback, delay); + } + setTimeout(callback, 0); return function(){ - clearInterval(iv); + self.stopped = true; + complete(observer); } }); } -const tick = _.overload(null, tick2(?, time), tick2); +function tick2(interval, f = time){ + return tick3(interval, 0, f); +} + +const tick = _.overload(null, tick2, tick2, tick3); function when2(interval, f){ return seed(f, tick(interval, f));