javascriptjqueryjquery-animate

How to delay the execution of a callback function in jQuery


I have two functions triggering animations (for opacity and top) on an element and its child, the second being the callback function of the first.

Between them there is a 5 second pause which I created by inserting .delay(5000) before animate(...) in the second function.

It works, but I am looking for a way to have that 5-second pause at the end of the first function instead.

The reason: I am making the execution of the second function dependent on the value of the buttonstate variable (which is set by clicking a button). But the function checks that value before the 5 second delay, which is not good, since the function is still executed if the stop button is pressed during these 5 seconds...

function fademove_1(slide_nr) {
    $(".slide_inner").css({"top": "70%", "opacity": "0.01"});
    $(".slide_" + slide_nr + " .slide_inner").delay(500).animate({
        top: "50%",
        opacity: 1
    }, 700, fadeout_1);
  }
function fadeout_1(slide_nr) {
    if(buttonstate != "stop"){
        $(".slide_" + slide_nr).delay(5000).animate({
          opacity: 0.01
        }, 2000);
    }

I simply can't find a way - everything I tried didn't work. Any suggestions what i could do?


Solution

  • The credit is due to @PitaJ, but here's how I solved it in my particular code. I erased the delay from the second function and appendend it (together with promise().then.(...)) to the first function, after the animation, as follows:

    function fademove_1(slide_nr) {
        $(".slide_inner").css({"top": "70%", "opacity": "0.01"});
        $(".slide_" + slide_nr + " .slide_inner").delay(500).animate({
            top: "50%",
            opacity: 1
        }, 700).delay(5000).promise().then(fadeout_1);;
      }
    function fadeout_1(slide_nr) {
        if(buttonstate != "stop"){
            $(".slide_" + slide_nr).animate({
              opacity: 0.01
            }, 2000);
        }