Javascript jQuery:等待/延迟 1 秒而不执行代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8896327/
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
jQuery: Wait/Delay 1 second without executing code
提问by Brian Graham
I can't get the .delaymethod working in jQuery:
我无法.delay在 jQuery 中使用该方法:
$.delay(3000); // not working
$(queue).delay(3000); // not working
I'm using a while loop to wait until an uncontrolled changing value is greater than or equal to another and I can't find any way to hault execution for X seconds.
我正在使用 while 循环来等待一个不受控制的变化值大于或等于另一个值,但我找不到任何方法来拖延 X 秒的执行。
回答by Matt Sich
You can also just delay some operation this way:
您也可以通过这种方式延迟一些操作:
setTimeout(function (){
// Something you want delayed.
}, 5000); // How long do you want the delay to be (in milliseconds)?
回答by Justin Niessner
$.delay is used to delay animations in a queue, not halt execution.
$.delay 用于延迟队列中的动画,而不是停止执行。
Instead of using a while loop, you need to recursively call a method that performs the check every second using setTimeout:
而不是使用 while 循环,您需要递归调用一个方法,该方法使用setTimeout以下方法每秒执行一次检查:
var check = function(){
if(condition){
// run when condition is met
}
else {
setTimeout(check, 1000); // check again in a second
}
}
check();
回答by thedanotto
ES6 setTimeout
ES6 设置超时
setTimeout(() => {
console.log("we waited 204586560000 ms to run this code, oh boy wowwoowee!");
}, 204586560000);
Edit: 204586560000 ms is the approximate time between the original question and this answer... assuming I calculated correctly.
编辑:204586560000 毫秒是原始问题和这个答案之间的大约时间......假设我计算正确。
回答by Julian D.
jQuery's delayfunction is meant to be used with effects and effect queues, see the delaydocsand the example therein:
jQuery 的delay函数旨在与效果和效果队列一起使用,请参阅delay文档和其中的示例:
$('#foo').slideUp(300).delay(800).fadeIn(400);
If you want to observe a variable for changes, you could do something like
如果你想观察一个变量的变化,你可以做类似的事情
(function() {
var observerInterval = setInterval(function() {
if (/* check for changes here */) {
clearInterval(observerInterval);
// do something here
}
}, 1000);
})();
回答by Jay Tomten
JavaScript setTimeoutis a very good solution:
JavaScriptsetTimeout是一个非常好的解决方案:
function funcx()
{
// your code here
// break out here if needed
setTimeout(funcx, 3000);
}
funcx();
The delayfunction in jQuery is mostly used for delaying animations in a jQuery animation queue.
delayjQuery 中的函数主要用于延迟 jQuery 动画队列中的动画。
回答by Nathan MacInnes
delay()doesn't halt the flow of code then re-run it. There's no practical way to do that in JavaScript. Everything has to be done with functions which take callbacks such as setTimeoutwhich others have mentioned.
delay()不会停止代码流然后重新运行它。在 JavaScript 中没有实用的方法可以做到这一点。一切都必须使用接受回调的函数来完成,例如setTimeout其他人提到的。
The purpose of jQuery's delay()is to make an animation queue wait before executing. So for example $(element).delay(3000).fadeIn(250);will make the element fade in after 3 seconds.
jQuery 的目的delay()是让动画队列在执行前等待。因此,例如$(element).delay(3000).fadeIn(250);将使元素在 3 秒后淡入。
回答by Faruk Omar
Only javascript It will work without jQuery
只有 javascript 它可以在没有 jQuery 的情况下工作
<!DOCTYPE html>
<html>
<head>
<script>
function sleep(miliseconds) {
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()) {
}
}
function hello() {
sleep(5000);
alert('Hello');
}
function hi() {
sleep(10000);
alert('Hi');
}
</script>
</head>
<body>
<a href="#" onclick="hello();">Say me hello after 5 seconds </a>
<br>
<a href="#" onclick="hi();">Say me hi after 10 seconds </a>
</body>
</html>
回答by Fabio Buda
Javascript is an asynchronous programming language so you can't stop the execution for a of time; the only way you can [pseudo]stop an execution is using setTimeout() that is not a delay but a "delayed function callback".
Javascript 是一种异步编程语言,因此您不能在一段时间内停止执行;您可以[伪]停止执行的唯一方法是使用 setTimeout() 这不是延迟而是“延迟函数回调”。
回答by Sapphire_Brick
It's as simple as this:
就这么简单:
function delay(seconds) {
var x = 0;
setTimeout(function() {
if(x){
return undefined;
}
x++;
}, seconds * 1000);
}
for(var x = 0; x < 5; x++){
alert("hi");
delay(10);
}
回答by Anthony De Smet
If you are using ES6 features and you're in an async function, you can effectively halt the code execution for a certain time with this function:
如果你正在使用 ES6 特性并且你在一个异步函数中,你可以使用这个函数有效地暂停代码执行一段时间:
const delay = millis => new Promise((resolve, reject) => {
setTimeout(_ => resolve(), millis)
});
This is how you use it:
这是你如何使用它:
await delay(5000);
It will stall for the requested amount of milliseconds, but only if you're in an async function. Example below:
它会在请求的毫秒数内停止,但前提是您在 async function 中。下面的例子:
const myFunction = async function() {
// first code block ...
await delay(5000);
// some more code, executed 5 seconds after the first code block finishes
}

