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]