markzzz markzzz - 4 years ago 97
Javascript Question

How can I create an Asynchronous function on Javascript?

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


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()

‚Äč

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download