Jason Axelrod Jason Axelrod - 3 months ago 13
Javascript Question

Cleaning up some ridiculous JS code

So I have some javascript for 3 html divs

mm
,
ss
and
pp
. These 3 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, then

  • pp
    hides, then

  • mm
    hides, then

  • divs get updated, then

  • mm
    shows, then

  • pp
    shows, then

  • ss
    shows, then



If
mm
doesn't change, but
pp
does, then:


  • ss
    hides, then

  • pp
    hides, then

  • divs get updated, then

  • pp
    shows, then

  • ss
    shows, then



If
mm
and
pp
don't change, but
ss
does, then:


  • ss
    hides, then

  • divs get updated, then

  • ss
    shows, then



I have this code running, but its 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.

Answer

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.