Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Long Polling
let ID = 1
const foo = document.createElement('p')
async function timeout (callback, delay) {
return await setTimeout(callback, delay)
}
function polling () {
return timeout(() => {
const xhr = new XMLHttpRequest(),
method = 'GET',
url = `https://jsonplaceholder.typicode.com/todos/${ID}`
xhr.open(method, url, true)
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log('responseText:', xhr.responseText)
}
}
xhr.onloadstart = () => console.log('Download started', new Date().getTime())
xhr.onload = e => {
const result = JSON.parse(e.target.response)
foo.innerText = result.title
result.completed && (foo.style.textDecoration = 'line-through')
document.body.prepend(foo)
ID++
polling()
}
xhr.onprogress = event => console.log('progress:' ,{
loaded: event.loaded,
total: event.total
})
xhr.onloadend = () => console.log('Download end', new Date().getTime())
xhr.onabort = () => console.warn('The request was aborted')
// xhr.abort()
xhr.ontimeout = () => console.error('Timeout!!')
xhr.onerror = event => console.error('Error:', event)
xhr.send()
}, 3000)
}
window.addEventListener('online', () => {
polling()
console.log('connection online!')
})
window.addEventListener('offline', () => {
polling()
console.log('connection offline!')
})
polling()
// or alternative: https://github.com/fanout/pollymer
// Server-Sent Events
// https://github.com/EventSource/eventsource
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment