emscripten-core/emscripten

A version of emscripten_sleep that uses requestAnimationFrame

Open

#9,574 创建于 2019年10月4日

在 GitHub 查看
 (10 评论) (0 反应) (0 负责人)C++ (3,519 fork)batch import
good first bughelp wantedwontfix

仓库指标

Star
 (27,361 star)
PR 合并指标
 (平均合并 19天 10小时) (30 天内合并 147 个 PR)

描述

With asyncify, emscripten_sleep becomes incredibly useful to implement game loops. However, the use of setTimeout means that the timing is inconsistent whereas requestAnimationFrame attempts to hold a consistent framerate.

Is there a version of this?

I am currently achieving it with this monkey patch:

const timeoutToAnimationId = {}
const originalSetTimeout = window.setTimeout;
const originalClearTimeout = window.clearTimeout;
window.setTimeout = (func, delay, ...args) => {
  if (typeof delay === 'undefined' || delay === 0) {
    const timeoutId = originalSetTimeout(() => {});
    const animationId = requestAnimationFrame(() =>
    {
      delete timeoutToAnimationId[timeoutId];
      func(...args);
    });
    timeoutToAnimationId[timeoutId] = animationId
    return timeoutId;
  } else {
    return originalSetTimeout(func, delay, ...args);
  }
}
window.clearTimeout = window.clearInterval = (timeoutId) => {
  const animationId = timeoutToAnimationId[timeoutId];
  if (typeof animationId !== 'undefined') {
    cancelAnimationFrame(animationId);
    delete timeoutToAnimationId[timeoutId];
  } else {
    return originalClearTimeout(id);
  }
}

贡献者指南