Skip to content

Commit d7789a4

Browse files
committed
simplify wait implementation
1 parent 4a9b025 commit d7789a4

File tree

3 files changed

+18
-19
lines changed

3 files changed

+18
-19
lines changed

src/__tests__/wait.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,14 @@ test('wait defaults to a noop callback', async () => {
1717
await wait()
1818
expect(handler).toHaveBeenCalledTimes(1)
1919
})
20+
21+
test('can timeout after the given timeout time', async () => {
22+
const error = new Error('throws every time')
23+
const result = await wait(
24+
() => {
25+
throw error
26+
},
27+
{timeout: 8, interval: 5},
28+
).catch(e => e)
29+
expect(result).toBe(error)
30+
})

src/wait-for-element.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import {wait} from './wait'
22

3+
// deprecated... TODO: remove this method. People should use a find* query or
4+
// wait instead the reasoning is that this doesn't really do anything useful
5+
// that you can't get from using find* or wait.
36
async function waitForElement(callback, options) {
47
if (!callback) {
58
throw new Error('waitForElement requires a callback as the first parameter')

src/wait.js

Lines changed: 4 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -23,20 +23,20 @@ function wait(
2323
} = {},
2424
) {
2525
if (interval < 1) interval = 1
26-
const maxTries = Math.ceil(timeout / interval)
27-
let tries = 0
2826
return new Promise((resolve, reject) => {
29-
let lastError, lastTimer
27+
let lastError
3028
const overallTimeoutTimer = setTimeout(onTimeout, timeout)
29+
const intervalId = setInterval(checkCallback, interval)
3130

3231
const observer = newMutationObserver(checkCallback)
3332
runWithRealTimers(() =>
3433
observer.observe(container, mutationObserverOptions),
3534
)
35+
checkCallback()
3636

3737
function onDone(error, result) {
3838
clearTimeout(overallTimeoutTimer)
39-
clearTimeout(lastTimer)
39+
clearInterval(intervalId)
4040
setImmediate(() => observer.disconnect())
4141
if (error) {
4242
reject(error)
@@ -58,21 +58,6 @@ function wait(
5858
function onTimeout() {
5959
onDone(lastError || new Error('Timed out in wait.'), null)
6060
}
61-
62-
function startTimer() {
63-
lastTimer = setTimeout(() => {
64-
tries++
65-
checkCallback()
66-
if (tries > maxTries) {
67-
onTimeout()
68-
return
69-
}
70-
startTimer()
71-
}, interval)
72-
}
73-
74-
checkCallback()
75-
startTimer()
7661
})
7762
}
7863

0 commit comments

Comments
 (0)