jQuery delay to work with append()

前端 未结 3 2052
眼角桃花
眼角桃花 2021-02-15 12:10

I can\'t make the delay function of jQuery works with append function. What is wrong? Is there a way to make it work? I want to avoid using setTimeout

相关标签:
3条回答
  • 2021-02-15 12:42

    This is because delay(2000) queues the fx queue by default, which append() is never part of.

    Instead, you can specifically queue append() on it using the queue() function.

    $('#chatwindow').append('test').delay(2000).queue(function (next) {
        $(this).append('test');
        next();
    });
    

    You can see an example of this working here; http://jsfiddle.net/mj8qC/

    However, I agree with @ascii-lime's comment; I expect the customer will have more chance understanding setTimeout as it's a fundamental part of JavaScript, unlike delay(), which confuses many users (from experience on questions asked on StackOverflow).

    FWIW, this question triggered me to write a blog post on the uses of delay(); it goes into more detail than this answer, and might be great further reading for others.

    0 讨论(0)
  • 2021-02-15 12:53

    delay() is a tricky function that can't be use with anything : it's mainly made for effects (it returns immediately, it doesn't block the javascript execution flow).

    From the doc :

    It can be used with the standard effects queue or with a custom queue

    (so you have to use a custom queue if you're not using the fx queue)

    Use setTimeout in this case.

    0 讨论(0)
  • 2021-02-15 13:01

    Yes. The return from delay is immediate. Nothing in your code suggest that the reurn should wait. You need to use setTimeout for the engine to wait..

    0 讨论(0)
提交回复
热议问题