0

Can I resolve the following issue with the use of a Promise? I am grabbing the body element and setting a 5s transition on it to increase height and then having the function call itself again to reduce the height, and so on and so on. The obvious issue is that function will repeatedly call itself before the font size has finished transitioning.

function swap(height=null) {
   let body = document.body;
    console.log("height = " , height);
    if (!height || height == '50px') {
      height = '20px'
    } else {
      height = '50px'
    }

   [...body.children].forEach(child => {
       child.style.fontSize = height;
       child.style.transition = 'all 5s ease';
   });
   swap(height)
}

I think one solution would be to just wrap the swap(height) in a setTimeout but is there any way a Promise can be used here? I am still trying to wrap my head around use-cases for them.

LegoGeo
  • 143
  • 6
  • 1
    use setTimeout and promise together – underscore Dec 12 '20 at 06:17
  • 4
    You can consider using [transition events](https://stackoverflow.com/questions/2794148/css3-transition-events) – PIG208 Dec 12 '20 at 06:20
  • A promise alone won't help with anything. You would specifically need a promise for a timeout or for the transition end event. And of course you can write such code without promises as well. – Bergi Dec 12 '20 at 07:10
  • @FarazShaikh Promises do not need to be `return`ed to do something useful with them. – Bergi Dec 12 '20 at 07:12

2 Answers2

1

You can use promises here. Here's how you might go about doing it with async/await syntax

const wait = ms => new Promise(resolve => setTimeout(resolve, ms))

async function swap(height=null) {
   // ...
   [...body.children].forEach(child => {
       child.style.fontSize = height;
       child.style.transition = 'all 5s ease';
   });
   await wait(5000);
   swap(height)
}

This really isn't much different from your suggestion of using setTimeout. All we're doing here is making our own version of setTimeout (called wait), that has a promise API instead of a callback one, allowing our async swap function to consume it more easily.

Scotty Jamison
  • 10,498
  • 2
  • 24
  • 30
  • 1
    Instead of a recursive call, with `async`/`await` you'd probably use a `while (true)` loop though. – Bergi Dec 12 '20 at 07:11
0

In this special case it's better to use an event actually. Since you are waiting for the transition to end, use the transitionEnd event. So you can be sure, it always fires at the right time, even if you change the transition time.

Andre
  • 458
  • 5
  • 10