diff --git a/src/reanimated2/threads.ts b/src/reanimated2/threads.ts index 4bae61baec3..8e18caf6b77 100644 --- a/src/reanimated2/threads.ts +++ b/src/reanimated2/threads.ts @@ -15,6 +15,7 @@ export function setupMicrotasks() { 'worklet'; let microtasksQueue: Array<() => void> = []; + let isExecutingMicrotasksQueue = false; // @ts-ignore – typescript expects this to conform to NodeJS definition and expects the return value to be NodeJS.Immediate which is an object and not a number global.queueMicrotask = (callback: () => void): number => { @@ -23,11 +24,19 @@ export function setupMicrotasks() { }; global.__callMicrotasks = () => { - for (let index = 0; index < microtasksQueue.length; index += 1) { - // we use classic 'for' loop because the size of the currentTasks array may change while executing some of the callbacks due to queueMicrotask calls - microtasksQueue[index](); + if (isExecutingMicrotasksQueue) { + return; + } + try { + isExecutingMicrotasksQueue = true; + for (let index = 0; index < microtasksQueue.length; index += 1) { + // we use classic 'for' loop because the size of the currentTasks array may change while executing some of the callbacks due to queueMicrotask calls + microtasksQueue[index](); + } + microtasksQueue = []; + } finally { + isExecutingMicrotasksQueue = false; } - microtasksQueue = []; }; }