安排工作在触发其他操作后进行
Schedule work to happen after someting else triggered
JS中是否有一种简单的方法可以做这样的事情:
var scheduler = ???;
var init;
scheduler.schedule(() => console.log(init)); // does nothing
init = "Hello";
scheduler.start(); // print "Hello" because it was scheduled
scheduler.schedule(() => console.log(" world!")); // instantly print
// "world! " because the scheduler is already active.
我也忘了在CS中怎么称呼这个,这又叫什么?
我相信
您正在寻找的是事件管理。节点.js提供事件发射器。浏览器JS没有,但有很多库提供此功能。
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {
console.log('an event occurred!');
});
myEmitter.emit('event');
另一方面,您的代码看起来更像是延迟(一次性解析,而不是多触发器)。 jQuery提供了此功能。我不知道任何本机实现。最接近的是承诺,但承诺是"只读延迟"。它们在施工后不会暴露resolve
/reject
。
const deferred = $.Deferred();
deferred.then(function(){
console.log('the deferred resolved!');
});
deferred.resolve(); // logs
// Fires immediately since deferred is already resolved
deferred.then(function(){
console.log('the deferred resolved already!');
});
这是一个非常简单的调度程序的示例,没有库,如果你想看看它是如何工作的
"use strict";
class Scheduler {
constructor(start) {
this.queue = []
this.started = !!start
}
start() {
this.started = true
this.execute()
}
stop() {
this.started = false
}
execute() {
while(this.started && this.queue.length > 0) {
let fn = this.queue.pop()
fn()
}
}
schedule(fn, context) {
if (context) {
fn = fn.bind(context)
}
this.queue.push(fn)
this.execute()
}
}
const scheduler = new Scheduler()
let init
scheduler.schedule(() => console.log(init)) // does nothing
init = "Hello"
scheduler.start() // print "Hello" because it was scheduled
scheduler.schedule(() => console.log(" world!")) // instantly print
// "world! " because the scheduler is already active.
相关文章:
- Jquery未定义函数正在停止其他操作
- jQuery:暂停按钮可以暂停所有其他操作
- 安排工作在触发其他操作后进行
- 如果条件,则在其他操作之后调用 Redux 操作
- 如果匹配,则对数组中的每个项执行其他操作,如果使用jvectormaps
- 这是关于Jquery/JS的,如果我改变元素's HTML-我可以对它执行其他Jquery/JS操作吗
- 是jQuery 1.3.2导致此操作不起作用,还是其他原因
- Chrome 撤消“阻止此页面创建其他对话框”的操作
- 维基百科API解析操作仅返回“其他语言”部分
- 在构造函数之后运行其他操作
- 从服务器端操作脚本或其他内容调用PowerShell脚本
- 例如,如何编辑一个 HTML 文件的标题并使其对所有其他页面执行相同的操作,而无需手动更改所有页面
- imacros javascript,如果其他操作不正常的话
- Meteor:当页面刷新或其他页面位置时,如何保留dom操作
- Node.js:执行多个异步操作的最佳方式,然后执行其他操作
- 如何在不影响其他项目的情况下操作一组列表组项目
- 是否可以在HTML/JS中执行其他操作的同时锚定页面
- Javascript函数阻止Safari执行任何其他操作
- commandButton双重操作:保存并重定向到其他页面
- 可以Dart操作其他窗口中的HTML元素