jQuery如何具有异步功能? [英] How does jQuery have asynchronous functions?

查看:91
本文介绍了jQuery如何具有异步功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶我找不到明确的答案。所以,在jQuery中,你可以这样做:

I'm surprised I can't find a clear answer to this. So, in jQuery, you can do this:

$(someElements).fadeOut(1000);
$(someElements).remove();

其中,将启动fadeOut动画,但在1秒内完成执行之前,元素从DOM中删除。但这怎么可能呢?我一直在阅读JavaScript是单线程的(参见:是JavaScript保证是单线程的?)。我知道我可以这样做:

Which, will start a fadeOut animation, but before it finishes executing in the 1 second duration, the elements are removed from the DOM. But how is this possible? I keep reading the JavaScript is single threaded (see also: Is JavaScript guaranteed to be single-threaded?). I know I can do either:

$(someElements).fadeOut(1000).promise().done(function() { 
    $(someElements).remove();
});

甚至更好:

$(someElements).fadeOut(1000, function() { 
    $(this).remove(); 
});

我不明白JavaScript是如何在单线程中运行但我能够使用这些异步执行的jQuery函数,同时可以在不同的地方看到DOM的变化。它是如何工作的? 这个问题不是:我如何解决这个问题。

What I don't understand is how JavaScript runs in a "single thread" but I'm able to use these jQuery functions that execute asynchronously and visibly see the DOM change in different places at the same time. How does it work? This question is not: "How do I fix this".

推荐答案

jQuery动画(和漂亮的很多基于javascript的动画)使用计时器来运行他们的动画。对 .fadeOut()的调用只是启动动画,直到一段时间后才完成一系列计时器操作。

jQuery animations (and pretty much all javascript-based animations) use timers to run their animations. The call to .fadeOut() just STARTS the animation and it doesn't complete until some time later when a series of timer operations are done.

这仍然是单线程的。 .fadeOut()执行动画的第一步,它为下一步设置计时器,然后设置其余的javascript(包括。 remove())运行直到完成。当javascript线程结束并且计时器的时间流逝时,计时器将触发并且动画的下一步发生。最后,当动画的所有步骤都完成后,jQuery会调用动画的完成函数。这是一个允许你在动画完成时做某事的回调。

This is all still single-threaded. .fadeOut() does the first step of the animation, it sets a timer for the next step and then the rest of your javascript (including the .remove()) runs until completion. When that javascript thread finishes and the time elapses for the timer, the timer fires and the next step of the animation happens. Finally when all steps of the animation have completed, jQuery calls the completion function for the animation. That is a callback that allows you to do something when the animation is done.

这就是你解决这个问题的方法:

That is how you fix this issue:

$(someElements).fadeOut(1000, function() {
    $(this).remove();
});

您可以使用动画完成功能,只在动画完成后删除项目。

You use the animation completion function and only remove the item when the animation is done.

这篇关于jQuery如何具有异步功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆