0

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?

1

2 Answers 2

2
 $.when(f())

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.

Sign up to request clarification or add additional context in comments.

Comments

0

$.when takes a deffered value or a normal value . If normal value is passed it is called immediately and if deffered value is passed it is called at the time of operation completion For is not a async operation in javascript so it is executed immediately.Refer to below example for normal value passed inside when

 $.when({ x: 10 }).then(function (option) {
            alert(option.x);
        })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.