有没有比下面的pausecomp函数(取自此处)更好的方法来设计JavaScript中的睡眠?
function pausecomp(millis)
{
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < millis);
}
这不是JavaScript中的Sleep的重复-动作之间的延迟;我希望在函数的中间有一个真正的睡眠,而不是在代码执行之前有一段延迟。
一种非常简单的睡眠方式,它将与运行JavaScript的任何东西兼容。。。这段代码已经过500个条目的测试,CPU和内存的使用情况在我的web浏览器上仍然不可见。
这里有一个函数,它等待节点变为可见。。。
此函数创建一个新的上下文函数(){}以避免递归。我们在这个新上下文中放置了与调用者代码相同的代码。我们使用函数Timeout在几秒钟后调用我们的函数。
var get_hyper = function(node, maxcount, only_relation) {
if (node.offsetParent === null) {
// node is hidden
setTimeout(function () { get_hyper(node, maxcount, only_relation)},
1000);
return;
};
// Enter the code here that waits for that node becoming visible
// before getting executed.
};
可以使用带有递增较大值的闭包调用setTimeout()。
var items = ['item1', 'item2', 'item3'];
function functionToExecute(item) {
console.log('function executed for item: ' + item);
}
$.each(items, function (index, item) {
var timeoutValue = index * 2000;
setTimeout(function() {
console.log('waited ' + timeoutValue + ' milliseconds');
functionToExecute(item);
}, timeoutValue);
});
结果:
waited 0 milliseconds
function executed for item: item1
waited 2000 milliseconds
function executed for item: item2
waited 4000 milliseconds
function executed for item: item3
我同意其他海报。忙着睡觉是个坏主意。
但是,setTimeout不支持执行。它在超时设置后立即执行函数的下一行,而不是在超时过期后执行,因此无法完成睡眠所能完成的任务。
方法是将你的功能分解为前后两部分。
function doStuff()
{
// Do some things
setTimeout(continueExecution, 10000) // Wait ten seconds before continuing
}
function continueExecution()
{
// Finish doing things after the pause
}
确保你的函数名仍然准确地描述了每一块正在做的事情(即GatherInputThenWait和CheckInput,而不是funcPart1和funcPart2)
此方法实现了在超时之后才执行您决定的代码行的目的,同时仍然将控制权返回到客户端PC,以执行它排队的任何其他代码。
正如评论中指出的那样,这绝对不会在循环中工作。你可以做一些花哨的(丑陋的)黑客来让它在一个循环中工作,但总的来说,这只会导致灾难性的意大利面条代码。
对于浏览器,我同意使用setTimeout和setInterval。
但是对于服务器端代码,它可能需要一个阻塞函数(例如,这样可以有效地进行线程同步)。
如果您正在使用Node.js和Meteor,您可能遇到了在光纤中使用setTimeout的限制。下面是服务器端睡眠的代码。
var Fiber = require('fibers');
function sleep(ms) {
var fiber = Fiber.current;
setTimeout(function() {
fiber.run();
}, ms);
Fiber.yield();
}
Fiber(function() {
console.log('wait... ' + new Date);
sleep(1000);
console.log('ok... ' + new Date);
}).run();
console.log('back in main');
参见:Node.js光纤,睡眠