如何强制jQuery函数在更新文本之前完成淡入淡出动画?



我正在开发一个javascript应用程序,它从链接到聊天室的python程序接收消息。目标是让javascript应用程序将html段落的文本更新为每条聊天消息的"谢谢+用户",淡入,延迟,然后淡出。

我的问题是,如果我一次收到多条聊天消息,则每个聊天发件人的段落文本会立即更新,并且不会等待淡入淡出的动画。

现在,对于每条聊天消息,我每次收到聊天线路时都会调用下面的函数。

function fadeInfadeOutMessage(name) {
$('#twitchname').html("Thank you <br> " +  name).fadeIn(timeFade[0]).delay(timeFade[1]).fadeOut(timeFade[2])
}

我需要进行哪些更改才能在淡入淡出序列完成之前不允许更新 html?

所以承诺允许你完成行动,然后做一些事情。因此,查看下面的示例,我让我的消息div承诺在他的动画队列完成之前他不会做任何事情。第一个承诺立即生效,因为他没有做任何事情来开始。如果无事可做,承诺总是会立即触发。因此,无论我单击该按钮多少次,它总是等待完成它正在做的事情,然后再重新开始。

来源: https://api.jquery.com/promise/

小提琴:https://jsfiddle.net/pxospknj/

.JS:

// No changes to this function. Its our callback now.
// The thing that happens after promises complete
function fadeInfadeOutMessage(name) {
$('#somemessage').html("Thank you <br> " +  name).fadeIn(1000).delay(1000).fadeOut(1000);
}

$("#somebutton").on("click",
function () {
var element = $("#somemessage");
// Make the element promise us that when its done doing whatever
// its doing it will complete what we just asked it to do which
// is animate again.
element.promise().done(
function () {
fadeInfadeOutMessage("gary");
}
)
}
);

.HTML:

<button id="somebutton">go</button>
<div id="somemessage"></div>

====

=====================================好的,所以默认队列是针对效果的,因此在动画排队时会立即更新 HTML。Buuuuut 如果我们传入字符串并使用超快速动画伪造队列,然后在回调期间更新 html,然后再执行真正的动画,我们可以将其拉下来。

在这一点上,由于默认的效果队列,甚至不需要承诺,但它们在处理异步代码时非常强大,因此请记住它们并阅读它们以备将来使用。

小提琴:https://jsfiddle.net/pxospknj/4/

.HTML:

<button id="somebutton">go</button>
<div id="somemessage"></div>

.JS:

function fadeInfadeOutMessage(name) {
// Immediate hide so we know its hidden before updating and we can use
// the callback to update html while taking advantage of the effects queue
$('#somemessage').hide(0,
function() {
$(this).html("Thank you <br> " + name);
}).fadeIn(1000).delay(1000).fadeOut(1000);
// Proceed as normal with other animations
}
// Init our count so we see different strings updating properly
var count = 0;
$("#somebutton").on("click",
function() {
// Make sure we pass in string so it has scope
fadeInfadeOutMessage("gary" + count);
// Update count
count++;
}
);

最新更新