我无法让jQuery中的.delay
方法起作用:
$.delay(3000); // not working
$(queue).delay(3000); // not working
我正在使用一个while循环来等待一个不受控制的变化值大于或等于另一个值,但我找不到任何方法来暂停执行X秒钟。我无法让jQuery中的.delay
方法起作用:
$.delay(3000); // not working
$(queue).delay(3000); // not working
我正在使用一个while循环来等待一个不受控制的变化值大于或等于另一个值,但我找不到任何方法来暂停执行X秒钟。setTimeout(function (){
// Something you want delayed.
}, 5000); // How long you want the delay to be, measured in milliseconds.
$.delay被用来延迟动画队列中的动画,而不是停止执行。
你需要递归调用一个使用setTimeout
每秒钟执行一次检查的方法,而不是使用while循环:
var check = function(){
if(condition){
// run when condition is met
}
else {
setTimeout(check, 1000); // check again in a second
}
}
check();
setTimeout()
。 - Joshua PintersetTimeout(check,0);
。 - reverie_ssES6 setTimeout
setTimeout(() => {
console.log("we waited 204586560000 ms to run this code, oh boy wowwoowee!");
}, 204586560000);
编辑:204586560000毫秒是原问题和本回答之间的大致时间...假设我计算正确。
const delay = millis => new Promise((resolve, reject) => {
setTimeout(_ => resolve(), millis)
});
使用方法如下:
await delay(5000);
如果您在异步函数中,它会停顿请求的毫秒数,但仅在此情况下。以下是示例:
const myFunction = async function() {
// first code block ...
await delay(5000);
// some more code, executed 5 seconds after the first code block finishes
}
await setTimeout(_ => {}, millis);
然后移到下一行。 - Chantelle ChanjQuery 的 delay
函数是用于动画效果和队列的,参见delay
文档和其中的示例:
$('#foo').slideUp(300).delay(800).fadeIn(400);
如果你想观察一个变量的变化,你可以做如下操作:
(function() {
var observerInterval = setInterval(function() {
if (/* check for changes here */) {
clearInterval(observerInterval);
// do something here
}
}, 1000);
})();
JavaScript setTimeout
是一个非常好的解决方案:
function funcx()
{
// your code here
// break out here if needed
setTimeout(funcx, 3000);
}
funcx();
delay
函数在jQuery中主要用于延迟jQuery动画队列中的动画。
delay()
不能停止代码流然后重新运行它。在JavaScript中,没有实际的方法可以做到这一点,所有的操作都必须通过带回调参数的函数来完成,例如大家提到的setTimeout
。
jQuery的delay()
的目的是使动画队列在执行之前等待一段时间。因此,例如$(element).delay(3000).fadeIn(250);
将使元素在3秒后淡入。
Javascript是一种异步编程语言,所以你不能暂停执行代码;唯一能[伪]暂停执行的方式是使用setTimeout()
,它不是延迟而是“延迟函数回调”。
setTimeout()
的这种“睡眠”用法感兴趣,您可能想查看此线程https://dev59.com/jnNA5IYBdhLWcg3wdtpd#39914235 - Tms91 function sleep(num) {
let now = new Date();
let stop = now.getTime() + num;
while(true) {
now = new Date();
if(now.getTime() > stop) return;
}
}
sleep(1000); // 1 second
alert('here');
该函数获取当前时间的毫秒数,加上num
(即未来时间),其中num
是以毫秒为单位加到当前时间的。
无限循环开始检查当前时间,直到当前时间晚于前面所指定的时间,一旦发生这种情况,该函数停止运行并继续执行此函数调用后的任何内容。
只使用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>