ngr*_*od6 5 jquery function synchronous
有没有办法在另一个函数完成后运行一个函数?例如:
doSomething();
doSomethingElse();
Run Code Online (Sandbox Code Playgroud)
我只想在doSomething完成后运行doSomethingElse().这可能吗?
如果您的doSomething()函数异步执行某些操作(例如发出Ajax请求),那么您将需要doSomethingElse()为该异步请求进行回调,而不是在doSomething()返回后立即执行.
实际上你可以用jQuery做你想做的事(至少在某种意义上).它可以被认为有点hacky但工作完美无瑕.
只需在页面中包含一个您不用于其他任何内容的元素.比如某个空的div.
<div id="syncFnHolder"></div>
Run Code Online (Sandbox Code Playgroud)
然后包含JS与您的函数+ runMe我编写的函数.
function doSomething() { alert("First"); }
function doSomethingElse() { alert("Second"); }
function doSomethingElseThree() { alert("Third"); }
function runMe(fn, selec) {
return function() {
fn();
setTimeout(function() {
$(selec).dequeue("syncFnQueue");
}, 1000);
}
};
var selector = "#syncFnHolder";
//add three functions to a queue
$(selector).queue("syncFnQueue", runMe(doSomething, selector));
$(selector).queue("syncFnQueue", runMe(doSomethingElse, selector));
$(selector).queue("syncFnQueue", runMe(doSomethingElseThree, selector));
//start first function in queue (FIFO) others are triggered automatically
$(selector).dequeue("syncFnQueue");
Run Code Online (Sandbox Code Playgroud)
这将产生三个警报,它们之间的距离为1秒,表示"第一","第二","第三".
如果您不想延迟,请删除setTimeout并将呼叫保留$(selec).dequeue("syncFnQueue");.
如果您的函数需要参数,例如,doSomething(x,y,z)您需要使runMe函数适应更好的部分并以不同方式构造返回的函数.点击此处或发布新问题.