I am currently experimenting with asynchronous function-calls in jQuery and am stuck. Consider the following example:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
</head>
<body>
<script type="text/javascript">
f = function() {
alert("f1");
var x = 0;
for (var i = 0; i < 2500000000; i++) {
x++;
}
alert("f2");
}
$.when( f() ).done(alert("done"));
alert("moving on...");
</script>
</body>
</html>
I would expect the alert-messages in the following order: “f1”, “moving on…”, “f2”, “done”
But when I run the code in Chrome, what I get is this: “f1”, nothing happens for 10s, “f2”, “done”, “moving on…”. This doesn’t look asynchronous to me. Am I doing something wrong or is this the intended behavior? If so, what is the whole point of using the when-function and the callback? Couldn’t I just call the function f synchronously?
This calls
f()immediately (like any other function call), then passes the result to$.when.$.when()does not magically make a function asynchronous; it can only work with existing asynchronous operations (eg, AJAX).The only way to do actual multi-threading in Javascript is to use Web Workers.