Javascript Don';在内部动画完成之前,不要执行函数 简练的版本
假设我有一个使用jQuery动画的函数。我不希望在动画完成之前再次调用此函数 例如,当调用下面的函数时,我不希望在内部计时器例程完成之前再次调用它:Javascript Don';在内部动画完成之前,不要执行函数 简练的版本,javascript,jquery,concurrency,Javascript,Jquery,Concurrency,假设我有一个使用jQuery动画的函数。我不希望在动画完成之前再次调用此函数 例如,当调用下面的函数时,我不希望在内部计时器例程完成之前再次调用它: function doSomething() { ... blah blah blah ... someElement.fadeOut(999, function() { // Don't let doSomething get invoked until the fadeOut animation has finish
function doSomething() {
... blah blah blah ...
someElement.fadeOut(999, function() {
// Don't let doSomething get invoked until the fadeOut animation has finished
});
}
冗长的问题
我正在开发一个新闻标签小部件,在封面下面是一个无序列表。一次仅显示列表元素的子集。每隔五秒钟,列表中的第一项会淡出,然后从列表顶部删除并添加到列表底部
循环显示顶级新闻项目的功能如下所示:
function advanceTicker(id) {
// Get the first item
var firstItem = $(id + ' li:first');
var firstItemMarkup = firstItem.html();
// Fade out the first item then move it to the bottom
firstItem.fadeOut(999, function() {
$(this).remove(); // Remove the first item
// Tack the first item to the end of the list
$(id).append('<li style="display:none">' + firstItemMarkup + '</li>');
// Make the new first item visible
$(id + ' li:first').show();
});
}
上述方法感觉是错误的,闻起来像是竞争条件问题。我所知道的所有实现都是在单线程上下文中运行的,或者只允许在沙箱中存在单独的线程,这样我才真正看到您的实现没有问题。不要在JavaScript中阻塞-它会冻结UI。@Brian:我认为“阻塞”在这里使用的词是错误的-我相应地更新了问题标题。啊,在这种情况下,@chaospanion的答案对我来说似乎是合理的。@Scott。。。你想做这样的东西吗?是 啊这是正确的方法。网页是单线程的,事件处理程序总是运行到完成。
var inAnimation = false;
function advanceTicker(id) {
if (!inAnimation) {
inAnimation = true;
...
firstItem.fadeOut(999, function() {
...
inAnimation = false;
});
}
}