mar*_*zzz 136 javascript jquery asynchronous function
看看这段代码:
<a href="#" id="link">Link</a>
<span>Moving</span>
$('#link').click(function () {
console.log("Enter");
$('#link').animate({ width: 200 }, 2000, function() {
console.log("finished");
});
console.log("Exit");
});
Run Code Online (Sandbox Code Playgroud)
正如您在控制台中看到的那样,"animate"函数是异步的,它"分叉"事件处理程序块代码的流程.事实上 :
$('#link').click(function () {
console.log("Enter");
asyncFunct();
console.log("Exit");
});
function asyncFunct() {
console.log("finished");
}
Run Code Online (Sandbox Code Playgroud)
按照块代码的流程!
如果我想创建我function asyncFunct() { }的这种行为,我怎么能用javascript/jquery做到这一点?我认为这是不使用的策略 setTimeout()
pim*_*vdb 177
你不能做一个真正的自定义异步功能.您最终必须利用本机提供的技术,例如:
setIntervalsetTimeoutrequestAnimationFrameXMLHttpRequestWebSocketWorkeronload实际上,对于动画jQuery 使用 setInterval.
Šim*_*das 66
你可以使用一个计时器:
setTimeout( yourFn, 0 );
Run Code Online (Sandbox Code Playgroud)
(哪里yourFn是你的功能的参考)
或者,与Lodash:
_.defer( yourFn );
Run Code Online (Sandbox Code Playgroud)
延迟调用
func直到当前调用堆栈已清除.func在调用它时提供任何其他参数.
fid*_*der 29
在这里你有简单的解决方案(其他写关于它) http://www.benlesh.com/2012/05/calling-javascript-function.html
在这里你有以上的解决方案:
function async(your_function, callback) {
setTimeout(function() {
your_function();
if (callback) {callback();}
}, 0);
}
Run Code Online (Sandbox Code Playgroud)
测试1(可输出'1 x 2 3'或'1 2 x 3'或'1 2 3 x'):
console.log(1);
async(function() {console.log('x')}, null);
console.log(2);
console.log(3);
Run Code Online (Sandbox Code Playgroud)
测试2(将始终输出'x 1'):
async(function() {console.log('x');}, function() {console.log(1);});
Run Code Online (Sandbox Code Playgroud)
该函数在超时0时执行 - 它将模拟异步任务
Eth*_*gue 10
这是一个函数,它接受另一个函数并输出一个运行异步的版本.
var async = function (func) {
return function () {
var args = arguments;
setTimeout(function () {
func.apply(this, args);
}, 0);
};
};
Run Code Online (Sandbox Code Playgroud)
它用作创建异步函数的简单方法:
var anyncFunction = async(function (callback) {
doSomething();
callback();
});
Run Code Online (Sandbox Code Playgroud)
这与@ fider的答案不同,因为函数本身有自己的结构(没有添加回调,它已经在函数中),还因为它创建了一个可以使用的新函数.
promises最近,但是为了展示在ES6中引入后使用的简单解决方案,它处理异步调用要容易得多:
您以新的承诺设置了异步代码:
var asyncFunct = new Promise(function(resolve, reject) {
$('#link').animate({ width: 200 }, 2000, function() {
console.log("finished");
resolve();
});
});
Run Code Online (Sandbox Code Playgroud)
请注意resolve()在异步调用结束时进行设置。
然后.then(),在promise中添加要在异步调用完成后运行的代码:
asyncFunct.then((result) => {
console.log("Exit");
});
Run Code Online (Sandbox Code Playgroud)
这是它的一个片段:
var asyncFunct = new Promise(function(resolve, reject) {
$('#link').animate({ width: 200 }, 2000, function() {
console.log("finished");
resolve();
});
});
Run Code Online (Sandbox Code Playgroud)
asyncFunct.then((result) => {
console.log("Exit");
});
Run Code Online (Sandbox Code Playgroud)