Skip to content

Instantly share code, notes, and snippets.

@lubien
Last active February 16, 2017 04:01
Show Gist options
  • Save lubien/f4049983a52b101cdf291e13fddb7c31 to your computer and use it in GitHub Desktop.
Save lubien/f4049983a52b101cdf291e13fddb7c31 to your computer and use it in GitHub Desktop.
Promise races
const $page = document.getElementById('page')
let currentPage = 0
const setPage = title => {
$page.innerText = title
}
const loadPage = (title, time) =>
new Promise(resolve =>
setTimeout(() => resolve(title), time)
)
const pageChanged = () =>
new Promise((_, reject) => {
const thisPage = currentPage
const interval = setInterval(() => {
if (thisPage !== currentPage) {
reject(interval)
}
}, 100)
})
.catch(interval => {
throw 'Loading stopped, route changed'
})
const onClickChangePage = button =>
button.addEventListener('click', () => {
const nextPage = button.getAttribute('data-page')
const delay = +button.getAttribute('data-delay')
currentPage++
Promise.race([
loadPage(nextPage, delay),
pageChanged()
])
.then(setPage)
})
Array.from(document.getElementsByTagName('button'))
.map(onClickChangePage)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment