exp: messing with timing
This commit is contained in:
parent
6bf009aece
commit
acdb34c612
|
@ -20,6 +20,8 @@
|
|||
"build",
|
||||
"index.js",
|
||||
"index.js.map",
|
||||
"server.js",
|
||||
"server.js.map",
|
||||
"src",
|
||||
"test",
|
||||
"test.js",
|
||||
|
|
|
@ -1,23 +1,20 @@
|
|||
export const createLoop = (
|
||||
ticker,
|
||||
{
|
||||
frequency = 1 / 60,
|
||||
sampler = window.performance.now.bind(window.performance),
|
||||
} = {},
|
||||
frequency = 1 / 60,
|
||||
) => {
|
||||
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,
|
||||
);
|
||||
};
|
||||
|
||||
|
|
43
packages/timing/src/server.js
Normal file
43
packages/timing/src/server.js
Normal 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();
|
||||
};
|
Loading…
Reference in New Issue
Block a user