Last active
February 16, 2017 04:01
-
-
Save lubien/f4049983a52b101cdf291e13fddb7c31 to your computer and use it in GitHub Desktop.
Promise races
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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