I'm building a game with move.js
for animation, but it takes too long so when the player click on the right solution it displays the winning message before the right solution change it's color, so I used deferred object to fire an event and catch it when the animation ends.
Here's my code:
var deferred = new $.Deferred();
click(e);
//show message when game is over
$.when(deferred).then(function(){
if (this.checkIfWin()){
alert('you won !');
this.nextLevel();
}
});
function click(e){
move(e)
.set('background-color','black')
.delay('0.1s')
.end();
deferred.notify();
}
but it's not notified and the message doesn't show up.What am I missing here ?
Because animations in javascript are asynchronous (they run via timers), the only way to know when they are done is to hook into some sort of completion callback or completion notification.
I don't know move.js myself, but it looks like you can get such a callback by supplying a callback to the
.end(fn)
method. But, you will also have to fix your code becausethis
inthis.checkIfWin()
will not be the right value in either of these code blocks. I don't know what you want it to be (since you don't show that part of your code), but you will have to refer to some other object besidesthis
. In any case, here's the general structure of the code both with and without the use of a deferred.In this case, it doesn't look like you really need to use the deferred as you could just put the completion code right in the callback:
Edit, Added callback function to
.end()
to includedeferred.notify
. See comments , Move#end([fn])Try
jsfiddle http://jsfiddle.net/guest271314/4Av4Z/