-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolling.js
More file actions
44 lines (35 loc) · 1.07 KB
/
Copy pathpolling.js
File metadata and controls
44 lines (35 loc) · 1.07 KB
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
44
function apiCall() {
console.log("API called at", new Date().toLocaleTimeString())
// Simulate a random success response
return new Promise((resolve) => {
const isSuccess = Math.random() > 0.8
setTimeout(() => {
resolve({ success: isSuccess })
}, 1000) // simulate 1s API response delay
})
}
function poll(func, pollInterval = 5000, maxTimeout = 120000) {
const startTime = Date.now()
async function executePoll() {
const elapsed = Date.now() - startTime
if (elapsed >= maxTimeout) {
console.log("⏰ Stopping polling: timeout exceeded")
return
}
try {
const result = await func()
if (result.success) {
console.log("✅ Success! Stopping polling.")
return
}
// Retry after the specified interval
setTimeout(executePoll, pollInterval)
} catch (err) {
console.error("❌ Polling error:", err)
setTimeout(executePoll, pollInterval) // Optionally retry on error
}
}
executePoll()
}
// Usage
poll(apiCall, 5000, 120000) // poll every 5s, timeout after 2 mins