Skip to content

Instantly share code, notes, and snippets.

@laphilosophia
Created December 24, 2019 21:10
Show Gist options
  • Save laphilosophia/2b5c2b7c1c71a263aa58c0da3b5f28c7 to your computer and use it in GitHub Desktop.
Save laphilosophia/2b5c2b7c1c71a263aa58c0da3b5f28c7 to your computer and use it in GitHub Desktop.
// 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