-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
new sync.js
43 lines (36 loc) · 1.13 KB
/
new sync.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const syncToFirestore = () => {
return new Promise((resolve, reject) => {
setTimeout(reject, 300)
})
}
const defaultSyncTimer = () => ({
timer: null,
resolves: [],
rejects: [],
})
let syncTimer = defaultSyncTimer()
const resetSyncTimer = () => { syncTimer = defaultSyncTimer() }
const syncDebounceFn = () => {
return new Promise((resolve, reject) => {
if (syncTimer.timer !== null) {
clearTimeout(syncTimer.timer)
syncTimer.timer = null
}
syncTimer.timer = setTimeout(async () => {
try {
const result = await syncToFirestore() // this executes firebase SDK batch
syncTimer.resolves.forEach(r => r())
resetSyncTimer()
} catch (error) {
syncTimer.rejects.forEach(r => r())
resetSyncTimer()
}
}, 1000)
syncTimer.resolves.push(resolve)
syncTimer.rejects.push(reject)
})
}
const printRes = i => console.log(i, 'resolved', performance.now())
setTimeout(() => { syncDebounceFn().then(() => printRes(1)) }, 30)
setTimeout(() => { syncDebounceFn().then(() => printRes(2)) }, 60)
setTimeout(() => { syncDebounceFn().then(() => printRes(3)) }, 90)