javascript 如何使用 jQuery 的 delay() 作为 sleep()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3375948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use jQuery's delay() as a sleep()?
提问by Tony_Henrich
Can jQuery be used as a sleep() or wait() function? Suspending the execution of the statements after the wait. I tried $().delay(5000) but there was no 5 second wait. Is delay() only used in effects?
jQuery 可以用作 sleep() 或 wait() 函数吗?在等待之后暂停语句的执行。我试过 $().delay(5000) 但没有等待 5 秒。delay() 仅用于效果吗?
I am not looking for solutions which involve setTimeout delayed execution of another function or a CPU hogging solution. I want a sleep() function which can be reused in different scripts.
我不是在寻找涉及 setTimeout 延迟执行另一个函数或 CPU 占用解决方案的解决方案。我想要一个可以在不同脚本中重用的 sleep() 函数。
Addition:
添加:
I didn't mean to suggest a solution which doesn't use setTimeout at all. I have seen solutions which required to move all code after where the delay is needed into its own function so that setTimeout can call it. I don't want that. Either a self contained wrapper function for using setTimeout or use jQuery delay() in a dummy non visual effect just for the purpose of simulating a sleep function.
我并不是要建议一个根本不使用 setTimeout 的解决方案。我已经看到需要在需要延迟的地方将所有代码移动到它自己的函数中以便 setTimeout 可以调用它的解决方案。我不想要那个。用于使用 setTimeout 的自包含包装函数或在虚拟非视觉效果中使用 jQuery delay() 只是为了模拟睡眠功能。
回答by Russ Cam
You're going to be out of luck. Any sleep()function will most likely need to utilize setTimeout(or possibly setInterval). In fact, delay()itself uses setTimeout. From jQuery 1.4.2 source:
你会倒霉的。任何sleep()功能都最有可能需要使用setTimeout(或可能setInterval)。事实上,delay()它本身使用setTimeout. 来自 jQuery 1.4.2 源代码:
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
type = type || "fx";
return this.queue( type, function() {
var elem = this;
setTimeout(function() {
jQuery.dequeue( elem, type );
}, time );
});
},
.delay()only works with queues, which the effects use (the fxqueue). It is possible to use custom queues using .queue()
回答by Roger
This works wonderfully to me:
这对我来说非常有效:
http://benalman.com/projects/jquery-dotimeout-plugin/
http://benalman.com/projects/jquery-dotimeout-plugin/
$.doTimeout(3000,function(){
alert('yahoooooo!');
});
Examples:
例子:
http://benalman.com/code/projects/jquery-dotimeout/examples/delay-poll/
http://benalman.com/code/projects/jquery-dotimeout/examples/delay-poll/
回答by Weston C
Javascript (and by extension, jQuery) doesn't have a real "sleep" function. You can more or less abuse setTimeout & setInterval (and their derivatives, like delay) to simulate sleep, but you're usually better off just adapting to the setInterval/Timeout way of doing things... figure out what you want done, seal it off in a function, pass it as an argument to one of those two.
Javascript(以及扩展名 jQuery)没有真正的“睡眠”功能。您可以或多或少地滥用 setTimeout 和 setInterval(以及它们的衍生物,如延迟)来模拟睡眠,但通常最好只适应 setInterval/Timeout 的做事方式......弄清楚你想要做什么,密封它在函数中关闭,将其作为参数传递给这两者之一。
Edit:
编辑:
Okay, I see your edit. You really want a conventional sleep function. What follows is absolutelyan abuse and not at all what I'd recommend. But if I had to build one to save my life, here's how I'd do it: test how long a high number of loop cycles takes, do a statistically significant number of these tests, average the results, and use that information to define a function that roughly translates a given number of milliseconds into a number of loop cycles, which it then runs through.
好的,我看到你的编辑了。你真的想要一个传统的睡眠功能。接下来的内容绝对是一种滥用,而不是我所推荐的。但是如果我必须建立一个来挽救我的生命,我会这样做:测试大量循环周期需要多长时间,进行这些测试的统计显着数量,平均结果,并使用该信息来定义一个函数,它粗略地将给定的毫秒数转换为多个循环周期,然后它会运行这些循环周期。
In JavaScript:
在 JavaScript 中:
function timeloop(cycles) {
var start = new Date().getTime();
for(var j=0; j<cycles; j++);
var end = new Date().getTime();
return end-start;
}
var sleep = (function () {
var ms_tally = 0, i, s = 100, L = 10000;
for(i=0; i<s; i++)
ms_tally += timeloop(L);
var avg = ms_tally / i;
var ms_per_cycle = avg / L;
var cycles_per_ms = 1 / ms_per_cycle;
return eval('function (ms) { for(var k=0, z=ms*'+cycles_per_ms+'; k<z; k++); }');
})()
I wouldn't trust my life, health, or even $20 to the accuracy of the timing, though. If you need any degree of precision finer than half a second, the right way to do this in JavaScript is to trust the facilities built into whatever environment you're using... and in the browser, that's setInterval and setTimeout.
不过,我不会相信我的生命、健康,甚至 20 美元的时间准确性。如果您需要任何小于半秒的精度,那么在 JavaScript 中执行此操作的正确方法是信任您正在使用的任何环境中内置的工具……而在浏览器中,那就是 setInterval 和 setTimeout。
Edit #2:
编辑#2:
I see the recommendation for Ben Alman's doTimeout pluginin one of the comments. After looking it over, it's worth noting that it is a better idea than the abomination I have produced above in just about every way. It isn't quitethe comfortable sleep-y syntax we're often used to, and you still have to think about your code in functions in some marginal way, but at least you can still keep the sequential feel. If you can't bring yourself to use setTimeout/Interval directly, use doTimeout or something like it.
我在其中一条评论中看到了对Ben Alman 的 doTimeout 插件的推荐。仔细查看之后,值得注意的是,它几乎在各个方面都比我上面产生的可憎的想法更好。这不是很舒适sleep我们经常用来-y语法,你仍然不得不考虑在一些边缘的单向函数的代码,但至少你仍然可以保持连续的感觉。如果您不能让自己直接使用 setTimeout/Interval,请使用 doTimeout 或类似的东西。
回答by cryo
You are going to have to use setTimeoutor similar in some way if you don't want to chew CPU time.
setTimeout如果您不想占用 CPU 时间,您将不得不以某种方式使用或类似。
Here's an example:
下面是一个例子:
function myfn() {
// make it so that `myvar` is in scope and can
// be shared by both `fn1` and `fn2`
var myvar
function fn1() {
alert('foo')
// set `bar` in the above `myfn`'s scope (without `var`)
myvar = 'bar'
// sleep for 1.2 seconds
setTimeout(fn2, 1200)
}
function fn2() {
alert(myvar)
}
fn1()
}
myfn()
回答by kolunar
According to your question How to use jQuery's delay() as a sleep()?, and to answer this:
根据您的问题 How to use jQuery's delay() as a sleep()? ,并回答这个问题:
I tried $().delay(5000) but there was no 5 second wait. Is delay() only used in effects?
我试过 $().delay(5000) 但没有等待 5 秒。delay() 仅用于效果吗?
Have you already tried jQuery.queue() with delay()? for e.g.
您是否已经尝试过 jQuery.queue() 和 delay()?例如
$.fn.extend({
changeBgColor: function(color) {
return this.each(function() {
$(this).css("background-color", color);
});
}
});
$.fn.wait = function(mls, callback) {
return this.delay(mls).queue(function () {
$("span").text($(this).queue().length);
callback();
$(this).dequeue();
});
};
$(document).ready(function(){
$("#start").click(function(){
var div = $("div");
div.delay(1000).queue(function () {
$("span").text(div.queue().length);
div.css("background-color", "red").text("red");
$(this).dequeue();
}).delay(1000).queue(function (next) {
$("span").text(div.queue().length);
div.changeBgColor("green").text("green");
next();
});
div.wait(1000,function () {
div.changeBgColor("yellow").text("yellow");
}).wait(1000,function () {
div.changeBgColor("blue").text("blue");
});
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<p><button id="start">Start</button> <span></span></p>
<div style="display:inline-block;background:blue;height:100px;width:100px;"></div>
<div style="display:inline-block;background:blue;height:100px;width:100px;"></div>
</body>
</html>
The queue() method allows you to create a queue of functions to be executed on selected elements. The dequeue() method executes them in order.
queue() 方法允许您创建要在选定元素上执行的函数队列。dequeue() 方法按顺序执行它们。

