zoukankan      html  css  js  c++  java
  • javascript异步编程

    function longTimeOperation(){
    	console.log("this is long time operation");
    
    	setTimeout(function(){
    		console.log("the long time operation cost 5000 ms");
    		f2();
    	}, 5000);
    
    	var first = function first(){                                   //此处 函数名first可以去掉。
    		console.log("i am doing first");
    	}();
    
    	console.log(first);
    
    	function f2(){
    		console.log("this is f2, i am callback");
    	}
    
    }
    
    longTimeOperation();
    

      输出:

        

    this is long time operation
    i am doing first
    undefined                         //间隔5秒后执行
    the long time operation cost 5000 ms
    this is f2, i am callback

    var LongTimeOperation = function (taskID){
    	var id  = taskID;
    
    	this.go = function(test){
    		console.log("this is long time operation" + id);
    
    		var delay = parseInt((Math.random()*10000000)%5000);
    
    		setTimeout(function(){
    			console.log("the taskid "+ id +" operation cost "+ delay +" ms");
    			test();
    		}, delay);
    
    		var first = function (){
    			console.log("i am doing first");
    		}();
    
    		console.log(first);
    
    		function f2(){
    			console.log("this is f2");
    		}
    	};
    }
    
    function second(){
    	console.log("second");
    }
    
    
    for(var i = 0; i < 5; i++){
    	var task = new LongTimeOperation(i);
    	task.go(second);
    }
    

      输出:

    this is long time operation0
    i am doing first
    undefined
    this is long time operation1
    i am doing first
    undefined
    this is long time operation2
    i am doing first
    undefined
    this is long time operation3
    i am doing first
    undefined
    this is long time operation4
    i am doing first
    undefined
    the taskid 1 operation cost 670 ms
    second
    the taskid 3 operation cost 1157 ms
    second
    the taskid 4 operation cost 2373 ms
    second
    the taskid 2 operation cost 2939 ms
    second
    the taskid 0 operation cost 4929 ms
    second
    [Finished in 5.1s]

  • 相关阅读:
    清除缓存
    框架更新 (简)
    Xutils简
    动画
    夜间模式
    TabLoaout简单框架
    atomic原子类的理解
    单例模式中指令重排序及需要使用volatile的理解
    对volatile的理解
    jvm内存模型及垃圾回收GC
  • 原文地址:https://www.cnblogs.com/z360519549/p/7266102.html
Copyright © 2011-2022 走看看