exp: messing with timing

This commit is contained in:
cha0s 2022-03-23 01:03:53 -05:00
parent 6bf009aece
commit acdb34c612
3 changed files with 53 additions and 11 deletions

View File

@ -20,6 +20,8 @@
"build",
"index.js",
"index.js.map",
"server.js",
"server.js.map",
"src",
"test",
"test.js",

View File

@ -1,23 +1,20 @@
export const createLoop = (
ticker,
{
frequency = 1 / 60,
sampler = window.performance.now.bind(window.performance),
} = {},
) => {
let lastTime = sampler();
let remain = 0;
let lastTime = window.performance.now();
let accumulate = 0;
return setInterval(
() => {
const now = sampler();
remain += (now - lastTime) / 1000;
const now = window.performance.now();
accumulate += (now - lastTime) / 1000;
lastTime = now;
while (remain > frequency) {
if (accumulate >= frequency) {
ticker(frequency);
remain -= frequency;
accumulate -= frequency;
}
},
3,
0,
);
};

View File

@ -0,0 +1,43 @@
import {performance} from 'perf_hooks';
export const createLoop = (
ticker,
frequency = 1 / 60,
) => {
let lastTime = performance.now();
let accumulate = 0;
let handle = {};
const loop = () => {
const now = performance.now();
accumulate += (now - lastTime) / 1000;
lastTime = now;
if (accumulate >= frequency) {
ticker(frequency);
accumulate -= frequency;
}
if (frequency - accumulate <= 0.005) {
handle.immediate = setImmediate(loop);
handle.timeout = null;
}
else {
handle.immediate = null;
handle.timeout = setTimeout(loop, 5);
}
};
handle.timeout = setTimeout(loop, 5);
return () => {
if (handle.immediate) {
clearImmediate(handle.immediate);
handle.immediate = undefined;
}
if (handle.timeout) {
clearTimeout(handle.timeout);
handle.timeout = undefined;
}
handle = {};
};
};
export const destroyLoop = (fn) => {
fn();
};