每天CookBook之JavaScript-034

  • 使用计时器和回调函数防止函数的阻塞
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>034</title>
</head>
<body>
    
</body>
<script type="text/javascript">
(function () {
    function factorial (n) {
     console.log(n);
     return n==1 ? 1:n*(factorial(n-1));
    }

    function noBlock (n, callback) {
         setTimeout(function(){
            var val = factorial(n);
            if(callback && typeof callback =='function'){
                callback(val);
            }
         },0);
    }

    console.log("Top of the morning to you");
    noBlock(3, function(n){
        console.log("first call ends with " + n);
        noBlock(n, function(m){
            console.log("final result is " + m);
        })
    });
})(); 
(function () {
    var tst = 0;
    for (var i = 0; i < 10; i++) {
        tst +=i;
    }
    console.log("vslue of tst is " + tst);
})(); 
</script>
</html>
posted @ 2016-07-14 22:13  4Thing  阅读(144)  评论(0编辑  收藏  举报