How can I create an Asynchronous function in Javascript?

哈哈:)我的codepen 的代码笔记是:http://codepen.io/shinewaker/pen/eBwPxJ

 -------------------------------------------------------

I mean, check it out this code :

<a href="#" id="link">Link</a>
<span>Moving</span>

$('#link').click(function () {
    console.log("Enter");
    $('#link').animate({  200 }, 2000, function() {
         console.log("finished");            
    });    
    console.log("Exit");    
});

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

follow the flow of the block code!

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
  • XMLHttpRequest
  • WebSocket
  • Worker
  • Some HTML5 APIs such as the File API, Web Database API
  • Technologies that support onload
  • ... many others

In fact, for the animation jQuery uses setInterval.

原文地址:https://www.cnblogs.com/oxspirt/p/6229154.html