1function waitFor(condition, MAX_FRAME = 500) { 2 return new Promise((resolve, reject) => { 3 function tick(frames) { 4 // We requestAnimationFrame either for MAX_FRAME frames or until condition is 5 // met. 6 if (frames >= MAX_FRAME) 7 reject(new Error(`Condition did not become true after ${MAX_FRAME} frames`)); 8 else if (condition()) 9 resolve(); 10 else 11 requestAnimationFrame(() => tick(frames + 1)); 12 } 13 tick(0); 14 }); 15} 16