interface IWaitForArgs { test: () => boolean // run function only if test() returns true interval: number count: number // should be 0, required maxAttempts: number // max number of attempts run: () => any // function to run } function waitFor({test, interval, count, maxAttempts, run}: IWaitForArgs) { // try to run function only maxAttempts times if (maxAttempts === count) { return } // Check if condition met. If not, re-check later. while (test() !== true) { count++ setTimeout(() => { waitFor({test, interval, count, maxAttempts, run}) }, interval) return } // Condition finally met. run() can be executed. run() } export default waitFor