如何在 Javascript 中创建异步函数? [英] How can I create an Asynchronous function in Javascript?
问题描述
看看这个代码:
<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");
});
正如您在控制台中看到的,animate"函数是异步的,它fork"了事件处理程序块代码的流程.事实上:
As you can see in the console, the "animate" function is asynchronous, and it "fork"s the flow of the event handler block code. In fact :
$('#link').click(function () {
console.log("Enter");
asyncFunct();
console.log("Exit");
});
function asyncFunct() {
console.log("finished");
}
跟着块码的流程走!
如果我想用这种行为创建我的 function asyncFunct() { }
,我该如何使用 javascript/jquery 来实现?我认为有一种不使用 setTimeout()
的策略
If I wish to create my function asyncFunct() { }
with this behaviour, how can I do it with javascript/jquery? I think there is a strategy without the use of setTimeout()
推荐答案
您无法制作真正自定义的异步函数.您最终将不得不利用本地提供的技术,例如:
You cannot make a truly custom asynchronous function. You'll eventually have to leverage on a technology provided natively, such as:
setInterval
setTimeout
requestAnimationFrame
XMLHttpRequest
WebSocket
工人
- 一些 HTML5 API,例如文件 API、Web 数据库 API
- 支持
onload
的技术 - ...许多其他
其实对于动画jQuery 使用 setInterval代码>.
In fact, for the animation jQuery uses setInterval
.
这篇关于如何在 Javascript 中创建异步函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!