Ela*_*ich 20 jquery asynchronous synchronous jquery-animate
在许多情况下,我希望动画同步执行.特别是当我想制作一系列连续动画时.
有一种简单的方法可以使jQuery animate函数调用同步吗?
我想到的唯一方法是在动画结束时将标志设置为true并等待此标志.
SLa*_*aks 26
jQuery无法制作同步动画.
请记住,JavaScript在浏览器的UI线程上运行.
如果您制作同步动画,浏览器将冻结,直到动画结束.
你为什么需要这样做?
您应该使用jQuery的回调参数并在回调中继续您的方法代码,如下所示:
function doSomething() {
var thingy = whatever;
//Do things
$('something').animate({ width: 70 }, function() {
//jQuery will call this method after the animation finishes.
//You can continue your code here.
//You can even access variables from the outer function
thingy = thingy.fiddle;
});
}
Run Code Online (Sandbox Code Playgroud)
这称为闭包.
我想你应该看一下jQuery queue()方法.
queue()的doc解释jQuery动画不仅没有真正阻止UI,而且实际上将它们排在一起.
它还提供了一种方法来使您的动画和函数调用顺序(这是我对" 同步 "的意思的最好理解),如:
$("#myThrobber")
.show("slow") // provide user feedback
.queue( myNotAnimatedMethod ) // do some heavy duty processing
.hide("slow"); // provide user feedback (job's
myNotAnimatedMethod() { // or animated, just whatever you want anyhow...
// do stuff
// ...
// tells #myThrobber's ("this") queue your method "returns",
// and the next method in the queue (the "hide" animation) can be processed
$(this).dequeue();
// do more stuff here that needs not be sequentially done *before* hide()
//
}
Run Code Online (Sandbox Code Playgroud)
这当然是异步处理的过度杀伤; 但是如果你的方法实际上是一个普通的旧同步javascript方法,那可能是这样做的方法.
希望这会有所帮助,抱歉我的英语不好......