Clearing some ridiculous JavaScript code

I have JavaScript for three HTML sections, mm , ss and pp . These three fields are animated with each other ... If the contents of an external file changes, these fields are updated on my page. They are updated with animation.

If mm changes, then:

  • ss hiding then
  • pp hides then
  • mm hide then
  • divs are updated then
  • mm shows then
  • pp shows then
  • ss shows then

If mm does not change, but pp does, then:

  • ss hiding then
  • pp hides then
  • divs are updated then
  • pp shows then
  • ss shows then

If mm and pp do not change, but ss does, then:

  • ss hiding then
  • divs are updated then
  • ss shows then

This code works for me, but it is very cumbersome, and I wonder 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 setTimeouts is all animations.

+7
javascript jquery
source share
1 answer

Use Promises and async / await .

Your code might 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 near Edge (and Chrome with a flag), so you need to use Babel to compile your code.

+5
source share

All Articles