javascript jQuery 延迟与 append() 一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11085567/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:03:30  来源:igfitidea点击:

jQuery delay to work with append()

javascriptjquery

提问by Jeff B.

I can't make the delay function of jQuery works with appendfunction. What is wrong? Is there a way to make it work? I want to avoid using setTimeoutdirectly to make it more easy to follow for the customer, who will maintain it himself, without any experience.

我无法使 jQuery 的延迟功能与append功能一起使用。怎么了?有没有办法让它工作?我想避免setTimeout直接使用,让客户更容易跟进,他们会自己维护,没有任何经验。

My code:

我的代码:

$('#chatwindow').append('test').delay(2000).append('test');

In this code, I get 'testtest' printed at the same time, delayis ignored.

在这段代码中,我同时打印了 'testtest',delay被忽略了。

回答by Matt

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

这是因为默认情况下delay(2000)fx队列进行排队,这append()从来不是其中的一部分。

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

相反,您可以append()使用该queue()函数专门对其进行排队。

$('#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/

您可以在此处查看此工作的示例;http://jsfiddle.net/mj8qC/

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

但是,我同意@ascii-lime 的评论;我希望客户有更多机会理解setTimeout它,因为它是 JavaScript 的一个基本部分,不像delay(),它让许多用户感到困惑(根据 StackOverflow 上提出的问题的经验)。

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

FWIW,这个问题促使我写了一篇关于使用的博客文章delay();它比这个答案更详细,对于其他人来说可能是很好的进一步阅读。

回答by Denys Séguret

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

delay()是一个棘手的函数,不能与任何东西一起使用:它主要用于效果(它立即返回,它不会阻止 javascript 执行流程)。

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)

(因此,如果您不使用 fx 队列,则必须使用自定义队列)

Use setTimeout in this case.

在这种情况下使用 setTimeout。

回答by srini.venigalla

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

是的。延迟的回报是立即的。您的代码中没有任何内容表明 reurn 应该等待。您需要使用 setTimeout 让引擎等待..