Appendix A. Hints for Selected Challenges
Here you’ll find solutions or hints for almost all the challenges in the book. Where an answer requires a significant amount of code, we make some suggestions but have left the coding to you.
A Replacement for the setTimeout Function
This is pretty easy:
function
wait
(
timeout
){
return
$
.
Deferred
(
function
(
deferred
){
setTimeout
(
deferred
.
resolve
,
timeout
);
}).
promise
();
}
You’d write something like this:
var
promise
=
wait
(
500
);
promise
.
done
(
function
(){
console
.
log
(
'Timeout fired!'
);
});
one
(
promise
);
two
(
promise
);
Of course the
one
andtwo
functions have to be able to accept a promise.We described this challenge as “subtly different” because it’s meant to demonstrate that our replacement
setTimeout
function is more than just a syntactic nicety. It gives you something you didn’t have before: a value that you can pass around to others. Although this is a trivial example, the principle is important.We just need to store the timeout identifier and add a function to the returning promise to clear the timeout and reject the deferred:
function
wait
(
timeout
){
var
deferred
=
$
.
Deferred
(),
promise
=
deferred
.
promise
(),
timeoutId
=
setTimeout
(
deferred
.
resolve
,
timeout
);
promise
.
cancel
=
function
(){
clearTimeout
(
timeoutId
);
deferred
.
reject
.
apply
(
deferred
,
arguments
);
};
return
promise
;
}
Note that this isn’t the best coding style. We probably shouldn’t be adding attributes to the promise in this way. How would you fix this shortcoming? While you’re at it, ...
Get Learning jQuery Deferreds now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.