mytimeout=setTimeout(myfunc,1000);
clearTimeout(mytimeout);
myInterval=setTimeout(myfunc,1000);
clearInterval(myInterval);
myImmediate=setTimeout(myfunc,1000);
clearImmediate(myImmediate);
myInterval=setTimeout(myfunc,1000);
myInterval.unref();
恢复引用
myInterval.ref();
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:如有问题,请大神之处
原文:http://www.cnblogs.com/dongzixiansheng/p/7020479.html