与gevent.sleep(0)等价的Javascript
在Python中,有一个名为的库,它支持协作多任务处理。有时,让两个长时间运行的函数互相执行是很有用的。例如:与gevent.sleep(0)等价的Javascript,javascript,python,multitasking,gevent,Javascript,Python,Multitasking,Gevent,在Python中,有一个名为的库,它支持协作多任务处理。有时,让两个长时间运行的函数互相执行是很有用的。例如: def long_running_func1(): while True: # processor intensive gevent.sleep() 呼叫使任务进入睡眠状态。没有参数,它只会让其他任务执行 在浏览器中使用Javascript,我发现自己需要类似的东西,以便在处理器密集型工作之间,UI有机会更新。比如: var data = []
def long_running_func1():
while True:
# processor intensive
gevent.sleep()
呼叫使任务进入睡眠状态。没有参数,它只会让其他任务执行
在浏览器中使用Javascript,我发现自己需要类似的东西,以便在处理器密集型工作之间,UI有机会更新。比如:
var data = [];
setTimeout(function () {
while (true) {
// Update UI with data.slice(data.length - 5, 5)
// gevent.sleep(0);
}
}, 0);
setTimeout(function () {
while (true) {
// var value = computation;
// data.append(value);
// gevent.sleep(0);
}
}, 0);
var LongTask = function() {
this.state = 0;
this.result = 'whatever';
};
LongTask.prototype.start = function(callback) {
async.whilst(
this._isFinished.bind(this),
this._doChunk.bind(this),
function(error) {
callback(error, this.result);
}
);
};
LongTask.prototype._isFinished = function() {
return this.state > 1000;
};
LongTask.prototype._doChunk = function(callback) {
var chunkEnd = this.state + 10;
while (this.state++ < chunkEnd) {
.... do something ...
}
// In NodeJS, you would call process.nextTick(callback)
setTimeout(callback, 0);
};
Javascript是否提供了某种允许这种模式的多任务处理
我一直使用的模式是将上述内容重写为:
var data = [];
function update_ui() {
// Update UI with data.slice(data.length - 5, 5)
}
function repeatedly() {
var value = computation;
data.append();
update_ui();
setTimeout(repeatedly, 0);
}
repeatedly();
但随着代码变得越来越复杂,这种模式不可避免地会涉及更多与setTimeout链接的函数,因此可读性不强
有比上面更好的模式吗?Javascript是自然事件驱动的,但您总是在单个线程上工作 IO是唯一总是异步处理的东西(浏览器javascript中没有阻塞IO函数) 如果您想进行长时间的计算,请将长时间的计算分割成块,并使用异步库为代码提供结构,同时避免锁定UI 比如:
var data = [];
setTimeout(function () {
while (true) {
// Update UI with data.slice(data.length - 5, 5)
// gevent.sleep(0);
}
}, 0);
setTimeout(function () {
while (true) {
// var value = computation;
// data.append(value);
// gevent.sleep(0);
}
}, 0);
var LongTask = function() {
this.state = 0;
this.result = 'whatever';
};
LongTask.prototype.start = function(callback) {
async.whilst(
this._isFinished.bind(this),
this._doChunk.bind(this),
function(error) {
callback(error, this.result);
}
);
};
LongTask.prototype._isFinished = function() {
return this.state > 1000;
};
LongTask.prototype._doChunk = function(callback) {
var chunkEnd = this.state + 10;
while (this.state++ < chunkEnd) {
.... do something ...
}
// In NodeJS, you would call process.nextTick(callback)
setTimeout(callback, 0);
};