jQuery: Wait/Delay 1 second without executing code

2019-01-21 01:49发布

I can't get the .delay method working in 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.

8条回答
Summer. ? 凉城
2楼-- · 2019-01-21 02:19

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 setTimeout which others have mentioned.

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.

查看更多
小情绪 Triste *
3楼-- · 2019-01-21 02:21

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)? 
查看更多
时光不老,我们不散
4楼-- · 2019-01-21 02:21

es6 setTimeout

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.

查看更多
仙女界的扛把子
5楼-- · 2019-01-21 02:25

Only javascript It will work without 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>
查看更多
爷的心禁止访问
6楼-- · 2019-01-21 02:27

jQuery's delay function is meant to be used with effects and effect queues, see the delay docs and the example therein:

$('#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);
})();
查看更多
孤傲高冷的网名
7楼-- · 2019-01-21 02:31

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".

查看更多
登录 后发表回答