Q:

About javascript setTimeout asynchronous mode

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        var i = 0;
        var d = 0;
        function BBB() {
            i++;
            alert("11");
            if (i <= 10)
                setTimeout("BBB()", 300);
        }
        function HHH() {
            d++;
            alert("22");
            if (d<= 10)
                setTimeout("HHH()", 300);
        }
        function CCC() {
            BBB();
            HHH();
        }
    </script>
</head>
<body>
    <input type="button" value="Submit" onclick="CCC()"/>
</body>
</html>

I would like to execute BBB function completely,then HHH function.
But the result is not so.The output is 11 22 11 11......
How to solve this?Sorry for my poor english! Thanks!

A:

setTimeout causes the functions to not be sequentially executed.
You would do what you do in any other asynchronous context ie 

Pass the function names as callback names
Keep a global variable to keep track
Use events.

In your case you have a variable i keeping track of the calls & hence Like this, perhaps :
 <script type="text/javascript">
        var i = 0;
        var d = 0;
        function BBB() {
            i++;
            alert("11");
            if (i <= 10)
                setTimeout("BBB()", 300);
            else HHH();
        }
        function HHH() {
            d++;
            alert("22");
            if (d<= 10)
                setTimeout("HHH()", 300);
        }
        function CCC() {
            BBB();
        }
    </script>

