1

Essentially, this is my code:

$('#press').click(function() { alert('First') });
$('#press').click(function() { alert('Second') });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="press">press</button>

How can I make sure if the second event handler-$('#press').click(secondFunction); is executed only after the first event handler-$('#press').click(firstFunction); is finished?

Yusril Maulidan Raji
  • 1,682
  • 1
  • 21
  • 46
  • Possible duplicate of [Jquery - Make sure event handler is last to be executed in chain of handlers](http://stackoverflow.com/questions/3150841/jquery-make-sure-event-handler-is-last-to-be-executed-in-chain-of-handlers) – Heretic Monkey Dec 20 '16 at 15:30

2 Answers2

3

How can I make sure the second event handler is executed only after the first event handler is finished?

Using your current pattern you can't. However you could call them sequentially inside a single event handler, like this:

var firstFunction = function() { alert('First') };
var secondFunction = function() { alert('Second') };
$('#press').click(function() {
  firstFunction();
  secondFunction();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="press">press</button>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
2

Use callbacks as shown below

var firstFunction = function(callback) {
  alert('First');
  callback();
};
var secondFunction = function() {
  alert('Second')
};

$('#press').click(function() {
  firstFunction(secondFunction);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="press">press</button>
Mike Scotty
  • 10,530
  • 5
  • 38
  • 50