From 28fbac0c6d1013ecff579614fcc7524592421414 Mon Sep 17 00:00:00 2001 From: pk Date: Tue, 25 Mar 2025 12:51:19 +0100 Subject: [PATCH] Add waitFor --- wait-for.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 wait-for.js diff --git a/wait-for.js b/wait-for.js new file mode 100644 index 0000000..109ec5d --- /dev/null +++ b/wait-for.js @@ -0,0 +1,28 @@ +/** + * Wait for some test to be true, returns a promise that resolves when condition is met. + * Useful to wait for element render, for example. Uses requestAnimationFrame. + * + * @param {Function} testFn Test function to call. Should return true to resolve and false to continue testing. + * @param {Number} maxTries Maximum number of rounds to test. If exceeded, the promise rejects. Defaults to 5000. + * @return {Promise} Promise that resolves when test passes or rejects when maxTries is reached + */ +export const waitFor = (testFn, maxTries = 5000) => { + return new Promise((resolve, reject) => { + let tries = 0; + const boundTestFn = testFn.bind(this); + + function waiter() { + if (tries === maxTries) { + return reject(new Error('waitFor: maximum tries exceeded')); + } + if (!boundTestFn()) { + window.requestAnimationFrame(waiter); + tries++; + return; + } + resolve(true); + } + + waiter(); + }); +} \ No newline at end of file