Run a function after executing another

function1 = function(){

  something.on('transitionend', function(){
    // now function2 should run
  });

}

function2 = function(){
  alert('ok');
}

function1();
function2();

So, I heard about jQuery promises. I would return a “deferred” object, and inside the event handler I would call deferred .resolve ();

But what happens if I have several event handlers and I want the next function to start when everyone has been fired? I don’t like the idea of ​​introducing something foreign, like “deferred” to other parts of the code.

Is there another way to determine if function 1 has completed all of its work?

+5
source share
3 answers

Try it,

 $.when($.ajax(fuction1())).then(function () {

    fuction2;

});

fuction1 - , fuction2 - .

+12

, .

function2 function1;

function1 = function(callback){

  something.on('transitionend', function(){
      callback();
  });

}

function2 = function(){
  alert('ok');
}

function1(function2);

... , function3 function2 function4 3.

;

function1 = function(){
  var def = new jQuery.Deferred();

  something.on('transitionend', function(){
      def.resolve(arguments);
  });

  return def.promise();
}

function2 = function(){
  alert('ok');
}

function1().done(function2);

..., , ( , promises, ).

. , , - , :

function1 = function(){
  var def = new jQuery.Deferred();
  var wait = 4;

  function maybeFire() {
      if (--wait) {
          def.resolve();
      }
  }

  something.on('transitionend', maybeFire);
  something.on('somethingelse', maybeFire);
  something.on('somethingelse', maybeFire);
  something.on('somethingelse', maybeFire);

  return def.promise();
}

function2 = function(){
  alert('ok');
}

function1().done(function2);

$.when(), , , , maybeFire.

+5

. transitionend , all css transition

( )

i.e.g.

HTML

<button>click</button>

CSS

button {
    width: 100px;
    -webkit-transition: width 1s;
}
.transition {
    width: 150px
}

JS

$(function() {
    // `$.Callbacks("once")` to fire `alert` once ,
    // even if `all` set within `css` `transition` 
    // property value
    var callbacks = $.Callbacks(); 

    function2 = function(j) {
      alert(j);
    };

    callbacks.add(function2);

    $(window).on("transitionComplete", function(e, i) {
     // function2(i);
        callbacks.fireWith($(this), [i]);
    });
    // `webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd`
    function1 = function() {
      $("button").on('transitionend', function (e) {
        $(window).trigger("transitionComplete", ["ok"]);
      });
    };

    function1();

    $("button").on("click", function(e) {
      $(this).toggleClass("transition");
    });

});

jsfiddle http://jsfiddle.net/guest271314/u7B9K/

+1

All Articles