nodeTimer.scheduleCancel = () => {
// 定时器取消
cancelTimer.cancel();
console.log('定时器成功取消');
}
调用:
nodeTimer.scheduleCancel()效果:

三,队列
第一步:安装async
npm install --save async第二步:封装方法
queue相当于一个加强版的parallel,主要是限制了worker数量,不再一次性全部执行。当worker数量不够用时,新加入的任务将会排队等候,直到有新的worker可用。
该函数有多个点可供回调,如worker用完时、无等候任务时、全部执行完时等。
const async = require('async');
/**
*队列
* @param obj :obj对象 包含执行时间
* @param callback :回调函数
*/
const nodeQueue = async.queue(function (obj, callback) {
setTimeout(function () {
// 需要执行的代码的回调函数
if(typeof callback==='function'){
callback();
}
}, obj.time)
}, 1)// worker数量将用完时,会调用saturated函数
nodeQueue.saturated = function() {
console.log('all workers to be used');
}
// 当最后一个任务交给worker执行时,会调用empty函数
nodeQueue.empty = function() {
console.log('no more tasks wating');
}
// 当所有任务都执行完时,会调用drain函数
nodeQueue.drain = function() {
console.log('all tasks have been processed');
}
module.exports = nodeQueue;
第三步:调用方法
const nodeQueue = require('./node_queue.js');
for (let i = 0; i < 10; i++) {
nodeQueue.push({ name: 1, time: 2000 }, function (err) {
console.log('队列执行错误信息==',err);
if(!err){
// 需要执行的代码或函数
console.log('需要执行的代码或函数第',i+1,'个')
}
})
};效果:

总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对软件开发网的支持。









