I have some JavaScript for three HTML divs, mm
, ss
and pp
. These three fields are animated with each other... If the contents of an external file change, these fields get updated in my page. They get updated with animations.
If mm
changes, then:
ss
hides, thenpp
hides, thenmm
hides, thenmm
shows, thenpp
shows, thenss
shows, thenIf mm
doesn't change, but pp
does, then:
ss
hides, thenpp
hides, thenpp
shows, thenss
shows, thenIf mm
and pp
don't change, but ss
does, then:
ss
hides, thenss
shows, thenI have this code running, but it's extremely cumbersome, and I'm wondering if there is a better way to do what I am doing:
if ($('#mm').html() != mm) {
hideElem('.score');
setTimeout(function() {
hideElem('.player');
setTimeout(function() {
hideElem('.match');
setTimeout(function() {
updateElems();
setTimeout(function() {
showElem('.match');
setTimeout(function() {
showElem('.player');
setTimeout(function() {
showElem('.score');
}, inSpeed);
}, inSpeed);
}, outSpeed);
}, outSpeed);
}, outSpeed);
}, outSpeed);
} else if ($('#pp').html() != pp) {
hideElem('.score');
setTimeout(function() {
hideElem('.player');
setTimeout(function() {
updateElems();
setTimeout(function() {
showElem('.player');
setTimeout(function() {
showElem('.score');
}, inSpeed);
}, outSpeed);
}, outSpeed);
}, outSpeed);
} else if ($('#ss').html() != ss) {
hideElem('.score');
setTimeout(function() {
updateElems();
setTimeout(function() {
showElem('.score');
}, outSpeed);
}, outSpeed);
}
The reason for the setTimeouts are because of all the animations.
Use Promises and async/await.
Your code could look like this:
const wait = ms => new Promise(resolve => setTimeout(resolve, ms))
;(async () => {
if ($('#mm').html() !== mm) {
hideElem('.score')
await wait(outSpeed)
hideElem('.player')
await wait(outSpeed)
hideElem('.match')
await wait(outSpeed)
updateElems()
await wait(outSpeed)
showElem('.match')
await wait(inSpeed)
showElem('.player')
await wait(inSpeed)
showElem('.score')
} else if ($('#pp').html() !== pp) {
hideElem('.score')
await wait(outSpeed)
hideElem('.player')
await wait(outSpeed)
updateElems()
await wait(outSpeed)
showElem('.player')
await wait(inSpeed)
showElem('.score')
} else if ($('#ss').html() !== ss) {
hideElem('.score')
await wait(outSpeed)
updateElems()
await wait(outSpeed)
showElem('.score')
}
})()
async/await is not yet supported in any browser beside Edge (and Chrome with flag), so you have to use Babel to compile your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With