emscripten-core/emscripten

A version of emscripten_sleep that uses requestAnimationFrame

Open

#9.574 aberto em 4 de out. de 2019

Ver no GitHub
 (10 comments) (0 reactions) (0 assignees)C++ (3.519 forks)batch import
good first bughelp wantedwontfix

Métricas do repositório

Stars
 (27.361 stars)
Métricas de merge de PR
 (Mesclagem média 19d 10h) (147 fundiu PRs em 30d)

Description

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);
  }
}

Guia do colaborador