简体   繁体   中英

javascript callback function after several jQuery calls

I got the following code:

$('#some_object_id').hide();
$('div#some_version_div').hide();
$('#some_another_object_id').show();
someFunction();

I want to issue my someFunction() only after the last of these 3 finishes its action. The problem is that from time to time they finish in different order (ie now the last may be the second, the other time the first one etc.) Now someFunction() fires without waiting for these 3 to finish. Any ideas how to fix it? Thank you.

jQuery's hide() and show() functions accept a function as their argument which is called when they finish. (aka, a callback).

$('selector').hide(function onFinish() {
  console.log('done')
})

To combine three of them together, I'd convert them to a Promise, like so:

function promisify(func,selector){
  return new Promise(function (resolve) {
    $(selector)[func](resolve)
  })
}

Promise.all([
  promisify('hide', '#test'),
  promisify('hide', '#test1'),
  promisify('show', '#test2')
]).then(function onFinish() {
  console.log('done!')
})

You can pass a callback function to hide, and show that gets executed when the animation is complete. So if you want them to execute in order just call each one in the callback of the previous one.

$('#some_object_id,div#some_version_div').hide(()=>{
  $('#some_another_object_id').show(()=>{
    someFunction();
  });  
});

And if you want to prevent a bunch of inner callbacks, and not require each animation run dependent of the others, you could use a flag. Increment the flag in each callback, check to see if its at a certain value, and then execute your function if it is.

var flag = 0;
function incrementFlag(){
   flag++;
   if(flag>=2){
     flag=0;
     someFunction();
   }
}
$('#some_object_id,div#some_version_div').hide(incrementFlag);
$('#some_another_object_id').show(incrementFlag);  

You could also modify the above to use a Promise, but will leave that for you to try.

You should use a variable that you initially set to 0 and increase on every complete call. As soon as the variable hit the value 3 and can call your function:

var completed = 0;
elem.hide(400, function(){
    completed++;
    if(completed > 2) someFunction();
});
//same for other elements...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM