我怎么能在JavaScript中创建一个异步函数? [英] How can I create an Asynchronous function in Javascript?

查看:192
本文介绍了我怎么能在JavaScript中创建一个异步函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的意思是,看看这个 code

I mean, check it out this code :

<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");    
});

你可以在控制台中看到,在动画功能是异步的,而且分支的事件处理程序块code的流量。事实上:

as you can see in console, the "animate" function is Asynchronous, and it "fork" 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");
}

按照块code的流量!

follow the flow of the block code!

如果我要创建我的函数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 use 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

  • XMLHtt prequest

  • 的WebSocket

  • 工人

  • 某些HTML5 API,如文件API,Web数据库API

  • 技术支持的onload

  • ...许多人

  • setInterval
  • setTimeout
  • requestAnimationFrame
  • XMLHttpRequest
  • WebSocket
  • Worker
  • Some HTML5 APIs such as the File API, Web Database API
  • Technologies that support onload
  • ... many others

事实上,对于动画jQuery的使用 的setInterval

In fact, for the animation jQuery uses setInterval.

这篇关于我怎么能在JavaScript中创建一个异步函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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