1 Node.js提供了四种形式的定时器 2 global.setTimeout(); //一次性定时器 3 global.setInterval(); //周期性定时器 4 global.nextTick(); //本次事件循环结束时立即执行的定时器 5 global.setImmediate(); //下次事件循环立即执行的定时器 6 7 var i=1; 8 setTimeout(()=>{ 9 console.log(i); 10 },1000); 11 12 //1秒之后,打印出0,1,2,3,4 13 for(var i=1;i<=3;i++){ 14 setTimeout(()=>{ 15 console.log(i) 16 },1000) 17 } 18 19 //闭包 20 21 for(var i=1; i<=3; i++){ 22 setTimeout(outer(i),1000) //定期定时器 23 } 24 function outer(num){ 25 return function(){ 26 console.log(num) 27 }; 28 } 29 30 //使用箭头函数完成上面的闭包功能 31 32 for(var i=1;i<=3;i++){ 33 setTimeout(((num)=>{ 34 return ()=>{console.log(num);}})(i),1000) 35 } 36 37 setInterval 周期性定时器 38 var count=0; 39 var timer=setInterval(function(){ 40 count++; 41 console.log('%d hello',count); 42 if(count>5){ 43 clearInterval(timer); 44 } 45 },1000); 46 47 //setTimeout 一次性定时器 48 var count2=0; 49 var timer2=setTimeout(function(){ 50 count2++; 51 if(count2<=5){ 52 console.log('%d hello',count2); 53 setTimeout(arguments.callee,1000); //arguments 54 }else{ 55 clearTimeout(timer2); 56 } 57 },1000)
1 //setImmediate(); 下次事件循环立即执行的定时器 2 setImmediate(function(){ 3 console.log('Immediate 1.....'); 4 }); 5 process.nextTick(function(){ 6 console.log('nextTick 1......'); 7 }); 8 setTimeout(function(){console.log('setTimeout 2....')},1000) 9 process.nextTick(function(){ 10 console.log('nextTick 2......'); 11 }); 12 setImmediate(function(){ 13 console.log('nextTick 3......'); 14 }); 15 console.log('end....');