Check out this code :
<a href="#" id="link">Link</a>
<span>Moving</span>
$('#link').click(function () {
console.log("Enter");
$('#link').animate({ width: 200 }, 2000, function() {
console.log("finished");
});
console.log("Exit");
});
As you can see in the console, the "animate" function is asynchronous, and it "fork"s the flow of the event handler block code. In fact :
$('#link').click(function () {
console.log("Enter");
asyncFunct();
console.log("Exit");
});
function asyncFunct() {
console.log("finished");
}
follow the flow of the block code!
If I wish to create my function asyncFunct() { }
with this behaviour, how can I do it with javascript/jquery? I think there is a strategy without the use of setTimeout()
You can use a timer:
(where
yourFn
is a reference to your function)or, with Lodash:
Here is a function that takes in another function and outputs a version that runs async.
It is used as a simple way to make an async function:
This is different from @fider's answer because the function itself has its own structure (no callback added on, it's already in the function) and also because it creates a new function that can be used.
Although not fundamentally different than the other solutions, I think my solution does a few additional nice things:
Function.prototype
allowing a nicer way to call itAlso, the similarity to the built-in function
Function.prototype.apply
seems appropriate to me.You cannot make a truly custom asynchronous function. You'll eventually have to leverage on a technology provided natively, such as:
setInterval
setTimeout
requestAnimationFrame
XMLHttpRequest
WebSocket
Worker
onload
In fact, for the animation jQuery uses
setInterval
.Next to the great answer by @pimvdb, and just in case you where wondering, async.js does not offer truly asynchronous functions either. Here is a (very) stripped down version of the library's main method:
So the function protects from errors and gracefully hands it to the callback to handle, but the code is as synchronous as any other JS function.
Late, but to show an easy solution using
promises
after their introduction in ES6, it handles asynchronous calls a lot easier:You set the asynchronous code in a new promise:
Note to set
resolve()
when async call finishes.Then you add the code that you want to run after async call finishes inside
.then()
of the promise:Here is a snippet of it:
or JSFiddle