mytimeout=setTimeout(myfunc,1000);數組
clearTimeout(mytimeout);dom
myInterval=setTimeout(myfunc,1000);函數
clearInterval(myInterval);ui
myImmediate=setTimeout(myfunc,1000);this
clearImmediate(myImmediate);spa
myInterval=setTimeout(myfunc,1000);prototype
myInterval.unref();code
恢復引用對象
myInterval.ref();blog
process.nextTick(callback)
Nodejs使用默認值爲1000的process.maxTickDepth來限制事件隊列的每次循環可執行的nextTick()時間數目。
事件使用一個EventEmitter對象來發出。這個對象在events模塊中。emit(eventName,[args])函數來觸發eventName事件,包括提供的任何參數
1 var event=require('event'); 2 var emitter=new event.EventEmitter(); 3 emitter.emit('simpleEvent');
把事件直接添加到本身的js對象。以下面:
function MyObj(){ Event.EventEmitter.call(this); } MyObj.prototype.__proto__=events.EventEmitter.prototype;
而後你就能夠直接從對象實例中發出事件。例如:
var myobj=new MyObj(); myobj.emit("someEvent");
var events=require("events"); function Account(){ this.balance=0; events.EventEmitter.call(this); this.deposit=function(amount){ this.balance+=amount; this.emit('balanceChanged'); }; this.withdraw=function(amount){ this.balance-=amount; this.emit('balanceChanged'); }; } Account.prototype.__proto__=events.EventEmitter.prototype; function checkOverdraw(){ if(this.balance<0){ console.log("哎媽呀,超支了!"); } } function displayBalance(){ console.log("Account balance: $%d",this.balance); } function checkGoal(acc,goal){ if(acc.balance>goal){ console.log("你是個有錢人!"); } } var account=new Account(); account.on("balanceChanged",displayBalance); account.on("balanceChanged",checkOverdraw); account.on("balanceChanged",function(){ checkGoal(this,1000); }); account.deposit(220); account.deposit(320); account.deposit(600); account.withdraw(1200);
回調的三個具體實現:將參數傳遞給回調函數,在循環內處理回調函數參數,以及嵌套回調。
向回調函數傳遞額外的參數的方法:在一個匿名函數中實現該參數,而後用來自匿名函數的參數調用回調函數。以下:
var events=require("events"); function CarShow(){ events.EventEmitter.call(this); this.seeCar=function(make){ this.emit("sawCar",make); }; } CarShow.prototype.__proto__=events.EventEmitter.prototype; var show=new CarShow(); function logCar(make){ console.log("Saw a "+make); } function logColorCar(make,color){ console.log("Saw a %s %s",color,make); } show.on("sawCar",logCar); show.on("sawCar",function(make){ var colors=['red','blue','black']; var color=colors[Math.floor(Math.random()*3)]; logColorCar(make,color); }); show.seeCar("喵喵"); show.seeCar("肥秒"); show.seeCar("可愛喵"); show.seeCar("美麗妙");
function logCar(car,callback){ console.log("Saw a %s ",car); if(cars.length){ process.nextTick(function(){ callback(); }); } } function logCars(cars){ var car=cars.pop(); logCar(car,function(){ logCars(cars); }); } var cars=["喵喵","妙妙","肥秒","純自然妙","傻逼喵","我愛的妙"]; logCars(cars);
PS:若有問題,請大神之處