RCTTiming.m 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. #import "RCTTiming.h"
  8. #import "RCTAssert.h"
  9. #import "RCTBridge+Private.h"
  10. #import "RCTBridge.h"
  11. #import "RCTLog.h"
  12. #import "RCTUtils.h"
  13. static const NSTimeInterval kMinimumSleepInterval = 1;
  14. // These timing contants should be kept in sync with the ones in `JSTimers.js`.
  15. // The duration of a frame. This assumes that we want to run at 60 fps.
  16. static const NSTimeInterval kFrameDuration = 1.0 / 60.0;
  17. // The minimum time left in a frame to trigger the idle callback.
  18. static const NSTimeInterval kIdleCallbackFrameDeadline = 0.001;
  19. @interface _RCTTimer : NSObject
  20. @property (nonatomic, strong, readonly) NSDate *target;
  21. @property (nonatomic, assign, readonly) BOOL repeats;
  22. @property (nonatomic, copy, readonly) NSNumber *callbackID;
  23. @property (nonatomic, assign, readonly) NSTimeInterval interval;
  24. @end
  25. @implementation _RCTTimer
  26. - (instancetype)initWithCallbackID:(NSNumber *)callbackID
  27. interval:(NSTimeInterval)interval
  28. targetTime:(NSTimeInterval)targetTime
  29. repeats:(BOOL)repeats
  30. {
  31. if ((self = [super init])) {
  32. _interval = interval;
  33. _repeats = repeats;
  34. _callbackID = callbackID;
  35. _target = [NSDate dateWithTimeIntervalSinceNow:targetTime];
  36. }
  37. return self;
  38. }
  39. /**
  40. * Returns `YES` if we should invoke the JS callback.
  41. */
  42. - (BOOL)shouldFire:(NSDate *)now
  43. {
  44. if (_target && [_target timeIntervalSinceDate:now] <= 0) {
  45. return YES;
  46. }
  47. return NO;
  48. }
  49. - (void)reschedule
  50. {
  51. // The JS Timers will do fine grained calculating of expired timeouts.
  52. _target = [NSDate dateWithTimeIntervalSinceNow:_interval];
  53. }
  54. @end
  55. @interface _RCTTimingProxy : NSObject
  56. @end
  57. // NSTimer retains its target, insert this class to break potential retain cycles
  58. @implementation _RCTTimingProxy
  59. {
  60. __weak id _target;
  61. }
  62. + (instancetype)proxyWithTarget:(id)target
  63. {
  64. _RCTTimingProxy *proxy = [self new];
  65. if (proxy) {
  66. proxy->_target = target;
  67. }
  68. return proxy;
  69. }
  70. - (void)timerDidFire
  71. {
  72. [_target timerDidFire];
  73. }
  74. @end
  75. @implementation RCTTiming
  76. {
  77. NSMutableDictionary<NSNumber *, _RCTTimer *> *_timers;
  78. NSTimer *_sleepTimer;
  79. BOOL _sendIdleEvents;
  80. }
  81. @synthesize bridge = _bridge;
  82. @synthesize paused = _paused;
  83. @synthesize pauseCallback = _pauseCallback;
  84. RCT_EXPORT_MODULE()
  85. - (void)setBridge:(RCTBridge *)bridge
  86. {
  87. RCTAssert(!_bridge, @"Should never be initialized twice!");
  88. _paused = YES;
  89. _timers = [NSMutableDictionary new];
  90. for (NSString *name in @[UIApplicationWillResignActiveNotification,
  91. UIApplicationDidEnterBackgroundNotification,
  92. UIApplicationWillTerminateNotification]) {
  93. [[NSNotificationCenter defaultCenter] addObserver:self
  94. selector:@selector(stopTimers)
  95. name:name
  96. object:nil];
  97. }
  98. for (NSString *name in @[UIApplicationDidBecomeActiveNotification,
  99. UIApplicationWillEnterForegroundNotification]) {
  100. [[NSNotificationCenter defaultCenter] addObserver:self
  101. selector:@selector(startTimers)
  102. name:name
  103. object:nil];
  104. }
  105. _bridge = bridge;
  106. }
  107. - (void)dealloc
  108. {
  109. [_sleepTimer invalidate];
  110. [[NSNotificationCenter defaultCenter] removeObserver:self];
  111. }
  112. - (dispatch_queue_t)methodQueue
  113. {
  114. return RCTJSThread;
  115. }
  116. - (void)invalidate
  117. {
  118. [self stopTimers];
  119. _bridge = nil;
  120. }
  121. - (void)stopTimers
  122. {
  123. if (!_paused) {
  124. _paused = YES;
  125. if (_pauseCallback) {
  126. _pauseCallback();
  127. }
  128. }
  129. }
  130. - (void)startTimers
  131. {
  132. if (!_bridge || ![self hasPendingTimers]) {
  133. return;
  134. }
  135. if (_paused) {
  136. _paused = NO;
  137. if (_pauseCallback) {
  138. _pauseCallback();
  139. }
  140. }
  141. }
  142. - (BOOL)hasPendingTimers
  143. {
  144. return _sendIdleEvents || _timers.count > 0;
  145. }
  146. - (void)didUpdateFrame:(RCTFrameUpdate *)update
  147. {
  148. NSDate *nextScheduledTarget = [NSDate distantFuture];
  149. NSMutableArray<_RCTTimer *> *timersToCall = [NSMutableArray new];
  150. NSDate *now = [NSDate date]; // compare all the timers to the same base time
  151. for (_RCTTimer *timer in _timers.allValues) {
  152. if ([timer shouldFire:now]) {
  153. [timersToCall addObject:timer];
  154. } else {
  155. nextScheduledTarget = [nextScheduledTarget earlierDate:timer.target];
  156. }
  157. }
  158. // Call timers that need to be called
  159. if (timersToCall.count > 0) {
  160. NSArray<NSNumber *> *sortedTimers = [[timersToCall sortedArrayUsingComparator:^(_RCTTimer *a, _RCTTimer *b) {
  161. return [a.target compare:b.target];
  162. }] valueForKey:@"callbackID"];
  163. [_bridge enqueueJSCall:@"JSTimers"
  164. method:@"callTimers"
  165. args:@[sortedTimers]
  166. completion:NULL];
  167. }
  168. for (_RCTTimer *timer in timersToCall) {
  169. if (timer.repeats) {
  170. [timer reschedule];
  171. nextScheduledTarget = [nextScheduledTarget earlierDate:timer.target];
  172. } else {
  173. [_timers removeObjectForKey:timer.callbackID];
  174. }
  175. }
  176. if (_sendIdleEvents) {
  177. NSTimeInterval frameElapsed = (CACurrentMediaTime() - update.timestamp);
  178. if (kFrameDuration - frameElapsed >= kIdleCallbackFrameDeadline) {
  179. NSTimeInterval currentTimestamp = [[NSDate date] timeIntervalSince1970];
  180. NSNumber *absoluteFrameStartMS = @((currentTimestamp - frameElapsed) * 1000);
  181. [_bridge enqueueJSCall:@"JSTimers"
  182. method:@"callIdleCallbacks"
  183. args:@[absoluteFrameStartMS]
  184. completion:NULL];
  185. }
  186. }
  187. // Switch to a paused state only if we didn't call any timer this frame, so if
  188. // in response to this timer another timer is scheduled, we don't pause and unpause
  189. // the displaylink frivolously.
  190. if (!_sendIdleEvents && timersToCall.count == 0) {
  191. // No need to call the pauseCallback as RCTDisplayLink will ask us about our paused
  192. // status immediately after completing this call
  193. if (_timers.count == 0) {
  194. _paused = YES;
  195. }
  196. // If the next timer is more than 1 second out, pause and schedule an NSTimer;
  197. else if ([nextScheduledTarget timeIntervalSinceNow] > kMinimumSleepInterval) {
  198. [self scheduleSleepTimer:nextScheduledTarget];
  199. _paused = YES;
  200. }
  201. }
  202. }
  203. - (void)scheduleSleepTimer:(NSDate *)sleepTarget
  204. {
  205. if (!_sleepTimer || !_sleepTimer.valid) {
  206. _sleepTimer = [[NSTimer alloc] initWithFireDate:sleepTarget
  207. interval:0
  208. target:[_RCTTimingProxy proxyWithTarget:self]
  209. selector:@selector(timerDidFire)
  210. userInfo:nil
  211. repeats:NO];
  212. [[NSRunLoop currentRunLoop] addTimer:_sleepTimer forMode:NSDefaultRunLoopMode];
  213. } else {
  214. _sleepTimer.fireDate = [_sleepTimer.fireDate earlierDate:sleepTarget];
  215. }
  216. }
  217. - (void)timerDidFire
  218. {
  219. _sleepTimer = nil;
  220. if (_paused) {
  221. [self startTimers];
  222. // Immediately dispatch frame, so we don't have to wait on the displaylink.
  223. [self didUpdateFrame:nil];
  224. }
  225. }
  226. /**
  227. * There's a small difference between the time when we call
  228. * setTimeout/setInterval/requestAnimation frame and the time it actually makes
  229. * it here. This is important and needs to be taken into account when
  230. * calculating the timer's target time. We calculate this by passing in
  231. * Date.now() from JS and then subtracting that from the current time here.
  232. */
  233. RCT_EXPORT_METHOD(createTimer:(nonnull NSNumber *)callbackID
  234. duration:(NSTimeInterval)jsDuration
  235. jsSchedulingTime:(NSDate *)jsSchedulingTime
  236. repeats:(BOOL)repeats)
  237. {
  238. if (jsDuration == 0 && repeats == NO) {
  239. // For super fast, one-off timers, just enqueue them immediately rather than waiting a frame.
  240. [_bridge _immediatelyCallTimer:callbackID];
  241. return;
  242. }
  243. NSTimeInterval jsSchedulingOverhead = MAX(-jsSchedulingTime.timeIntervalSinceNow, 0);
  244. NSTimeInterval targetTime = jsDuration - jsSchedulingOverhead;
  245. if (jsDuration < 0.018) { // Make sure short intervals run each frame
  246. jsDuration = 0;
  247. }
  248. _RCTTimer *timer = [[_RCTTimer alloc] initWithCallbackID:callbackID
  249. interval:jsDuration
  250. targetTime:targetTime
  251. repeats:repeats];
  252. _timers[callbackID] = timer;
  253. if (_paused) {
  254. if ([timer.target timeIntervalSinceNow] > kMinimumSleepInterval) {
  255. [self scheduleSleepTimer:timer.target];
  256. } else {
  257. [self startTimers];
  258. }
  259. }
  260. }
  261. RCT_EXPORT_METHOD(deleteTimer:(nonnull NSNumber *)timerID)
  262. {
  263. [_timers removeObjectForKey:timerID];
  264. if (![self hasPendingTimers]) {
  265. [self stopTimers];
  266. }
  267. }
  268. RCT_EXPORT_METHOD(setSendIdleEvents:(BOOL)sendIdleEvents)
  269. {
  270. _sendIdleEvents = sendIdleEvents;
  271. if (sendIdleEvents) {
  272. [self startTimers];
  273. } else if (![self hasPendingTimers]) {
  274. [self stopTimers];
  275. }
  276. }
  277. @end