Skip to content

Instantly share code, notes, and snippets.

@askdaddy
Created December 24, 2020 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save askdaddy/c8acb50c4ccc36ca5e65f2cefddd3495 to your computer and use it in GitHub Desktop.
Save askdaddy/c8acb50c4ccc36ca5e65f2cefddd3495 to your computer and use it in GitHub Desktop.
ts-loop base on setTimeout
export const fps: number = 10;
export const interval = fps > 0 ? 1000 / fps : 1000 / 30;
function _run(current: number, delta: number) {
console.log(`_run at ${current} + delta: ${delta}`);
// TODO do something here.
for(let i=0; i< 499999 ;++i){
let a = new Date().getTime() + i;
}
}
function update(current: number, delta: number = 0) {
_run(current, delta);
const now: number = new Date().getTime();
const run_time: number = now - current;
if (run_time >= interval) {
// I am late.
console.log(`Update late. run_time: ${run_time} `);
update(now, run_time);
} else{
console.log(`${interval - run_time}`);
setTimeout(() => {
const when: number = new Date().getTime();
update(when, when - now);
}, interval - run_time)
}
}
update(new Date().getTime());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment