Files
react-native/packages/react-native/ReactCommon/react/runtime/TimerManager.h
T
Phil Pluckthun 942422c4cb fix: Align TimerManager sequential ids and function error handling with web standard (#51500)
Summary:
Calls to create timers should return sequential ids (integers greater than zero in the spec's words). This regressed in the `TimerManager` implementation, which instead starts at zero inclusively.

This has two side-effects for code assuming a spec-compliant implementation of `setTimeout` and `setInterval`:
- Calls to `clearTimeout(0)` or `clearInterval(0)` will potentially cancel scheduled timers, although it's supposed to be a noop
- Predicates like `if (timeoutId)` will fail since they assume non-negative ids

The change in this PR is to align with WHATWG HTML 8.6.2 (Timers): https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers

> otherwise, let id be an [implementation-defined](https://infra.spec.whatwg.org/#implementation-defined) integer that is **greater than zero** and does not already [exist](https://infra.spec.whatwg.org/#map-exists) in global's [map of setTimeout and setInterval IDs](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#map-of-settimeout-and-setinterval-ids).

Specifically,
- we should return `0` to indicate that no timer was scheduled
- we should start generating timer IDs at `1` instead of `0`

This was previously raised in review comments here: https://github.com/facebook/react-native/pull/45092/files#r1650790008

The spec-incompliant behaviour was raised in an issue here: https://github.com/apollographql/apollo-client/issues/12632#issue-3075269978

This PR does not,
- add bounds checking on `timerIndex_` and add a search of an available id that isn't in the unordered map
- exclude `0` from being an accepted `TimerHandle` in `TimerManager::createTimer` or `TimerManager::deleteTimer` since the above bounds checking hasn't been added either

## Changelog:

[GENERAL] [FIXED] - Align timer IDs and timer function argument error handling with web standards.

Pull Request resolved: https://github.com/facebook/react-native/pull/51500

Test Plan:
- Run `setTimeout` / `setInterval`; before applied changes the timeout for the first timer will be `0`
- Run `setTimeout(null)`; before applied changes the timer ID will be non-zero
- Run `setInterval(null)`; before applied changes an error will be thrown rather than `0` being returned

Reviewed By: cipolleschi

Differential Revision: D75145909

Pulled By: rshest

fbshipit-source-id: 6646439abd29cf3cfa9e5cf0a57448e3b7cd1b48
2025-06-04 09:39:29 +00:00

107 lines
2.9 KiB
C++

/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <ReactCommon/RuntimeExecutor.h>
#include <cstdint>
#include <unordered_map>
#include <vector>
#include "PlatformTimerRegistry.h"
namespace facebook::react {
using TimerHandle = int;
enum class TimerSource {
Unknown,
SetTimeout,
SetInterval,
RequestAnimationFrame
};
/*
* Wraps a jsi::Function to make it copyable so we can pass it into a lambda.
*/
struct TimerCallback {
TimerCallback(
jsi::Function callback,
std::vector<jsi::Value> args,
bool repeat,
TimerSource source = TimerSource::Unknown)
: callback_(std::move(callback)),
args_(std::move(args)),
repeat(repeat),
source(source) {}
void invoke(jsi::Runtime& runtime) {
callback_.call(runtime, args_.data(), args_.size());
}
jsi::Function callback_;
const std::vector<jsi::Value> args_;
bool repeat;
TimerSource source;
};
class TimerManager {
public:
explicit TimerManager(
std::unique_ptr<PlatformTimerRegistry> platformTimerRegistry) noexcept;
void setRuntimeExecutor(RuntimeExecutor runtimeExecutor) noexcept;
void callReactNativeMicrotasks(jsi::Runtime& runtime);
void callTimer(TimerHandle handle);
void attachGlobals(jsi::Runtime& runtime);
private:
TimerHandle createReactNativeMicrotask(
jsi::Function&& callback,
std::vector<jsi::Value>&& args);
void deleteReactNativeMicrotask(jsi::Runtime& runtime, TimerHandle handle);
TimerHandle createTimer(
jsi::Function&& callback,
std::vector<jsi::Value>&& args,
double delay,
TimerSource source = TimerSource::Unknown);
void deleteTimer(jsi::Runtime& runtime, TimerHandle handle);
TimerHandle createRecurringTimer(
jsi::Function&& callback,
std::vector<jsi::Value>&& args,
double delay,
TimerSource source = TimerSource::Unknown);
void deleteRecurringTimer(jsi::Runtime& runtime, TimerHandle handle);
RuntimeExecutor runtimeExecutor_;
std::unique_ptr<PlatformTimerRegistry> platformTimerRegistry_;
// A map (id => callback func) of the currently active JS timers
std::unordered_map<TimerHandle, TimerCallback> timers_;
// Each timeout that is registered on this queue gets a sequential id. This
// is the global count from which those are assigned.
// As per WHATWG HTML 8.6.1 (Timers) ids must be greater than zero, i.e. start
// at 1
TimerHandle timerIndex_{1};
// The React Native microtask queue is used to back public APIs including
// `queueMicrotask`, `clearImmediate`, and `setImmediate` (which is used by
// the Promise polyfill) when the JSVM microtask mechanism is not used.
std::vector<TimerHandle> reactNativeMicrotasksQueue_;
};
} // namespace facebook::react