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()
here you have simple solution (other write about it) http://www.benlesh.com/2012/05/calling-javascript-function.html
And here you have above ready solution:
TEST 1 (may output '1 x 2 3' or '1 2 x 3' or '1 2 3 x'):
TEST 2 (will always output 'x 1'):
This function is executed with timeout 0 - it will simulate asynchronous task
MDN has a good example on the use of setTimeout preserving "this".
Like the following:
Edit: I totally misunderstood the question. In the browser, I would use
setTimeout
. If it was important that it ran in another thread, I would use Web Workers.If you want to use Parameters and regulate the maximum number of async functions you can use a simple async worker I've build:
You can use it like this:
Unfortunately, JavaScript doesn't provide an async functionality. It works only in a single one thread. But the most of the modern browsers provide
Worker
s, that are second scripts which gets executed in background and can return a result. So, I reached a solution I think it's useful to asynchronously run a function, which creates a worker for each async call.The code below contains the function
async
to call in background.This is an example for usage:
This executes a function which iterate a
for
with a huge number to take time as demonstration of asynchronicity, and then gets the double of the passed number. Theasync
method provides afunction
which calls the wanted function in background, and in that which is provided as parameter ofasync
callbacks thereturn
in its unique parameter. So in the callback function Ialert
the result.This page walks you through the basics of creating an async javascript function.
If that doesn't solve it for you, check out the documentation on the
animate
function.