2

Need to slideUp elements sequencially, one by one, not asynch.

block2 should start sliding when block1 is closed.

block3 should start sliding when block2 is closed.

And so on. In reality I have a lot of such elements so any nested syntax (function inside function) is not suitable.

I hope async await is the right way but cannot understand fully.

Here is my try:

$('button').on('click', function(){
close_all();
});
async function close_all(){
  await close1();
  await close2();
  await close3();
}
function close1(){
$('#block1').slideUp();
}
function close2(){
$('#block2').slideUp();
}
function close3(){
$('#block3').slideUp();
}
.block{
display:inline-block;
width:14%;
background:gold;
margin:0 9px;
}
#block1{
height:54px;
}
#block2{
height:25px;
}
#block3{
height:72px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='block' id='block1'>BLOCK 1</div>
<div class='block' id='block2'>BLOCK 2</div>
<div class='block' id='block3'>BLOCK 3</div>
<button>CLICK</button>
qadenza
  • 9,025
  • 18
  • 73
  • 126
  • I have updated with generic approach, if I found a way to do the same with `await` and `async` I will update again. – Shidersz Feb 12 '19 at 05:50

1 Answers1

1

One way could be using the on complete callback that you can use on the slideUp() method:

$('button').on('click', function()
{
    close_all($(".block"));
});

function close_all(elements, idx=0)
{
    if (idx >= elements.length)
        return;

    let cb = () => close_all(elements, idx + 1);    
    elements.eq(idx).slideUp(2000, cb);
}
.block {
  float: left;
  width:14%;
  background:gold;
  margin:0 9px;
}

#block1{
  height:54px;
}

#block2{
  height:25px;
}

#block3{
  height:72px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class='block' id='block1'>BLOCK 1</div>
<div class='block' id='block2'>BLOCK 2</div>
<div class='block' id='block3'>BLOCK 3</div>
<button>CLICK</button>
Shidersz
  • 16,846
  • 2
  • 23
  • 48
  • much better but what is the starting jumping, just after click – qadenza Feb 12 '19 at 05:51
  • @qadenza that was related to `display:inline-block` CSS property. I have changed it to `foat:left` for a similar layout. However I can't explain the issue related to using `display:inline-block`. – Shidersz Feb 12 '19 at 14:59
  • @qadenza I also have made a question about this issue: https://stackoverflow.com/questions/54653265/issue-with-displayinline-block-css-property – Shidersz Feb 12 '19 at 15:18