Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript, when do callback functions enter event queue?

Really trying to understand the event queue of javascript. My current understanding is the following.

Code:

let doSomething = (callback) => {
callback("first");
};

let foo = (text) => {
    console.log(text);
};

doSomething(foo);

setTimeout(() => {
    console.log("hey");
});

console.log("after");

Current knowledge:

The callback of doSomething is not an asynchronous operation so it is not placed in the callback queue. However, the setTimeout is an asynchronous operation and thus placed in the callback queue this. Because the callback queue is called upon after the javascript thread is finished, thus the setTimeout() function is called last.

Questions:

  1. Is my current understanding correct?
  2. What exactly makes an operation an asynchronous operation? Is this because Javascript itself has certain operations which are asynchronous by default?
  3. Can you make asynchronous operations yourself in javascript without the use of built in asynchronous operations like setTimeout()?
like image 617
Willem van der Veen Avatar asked Oct 25 '25 08:10

Willem van der Veen


1 Answers

Is my current understanding correct?

Yes, it will execute those functions in order. Since you call doSomething before you define the setTimeout it will finish first.

What exactly makes an operation an asynchronous operation? Is this because Javascript itself has certain operations which are asynchronous by default?

It is asynchronous when the execution of the code doesn't halt the execution of the main thread. JavaScript is single threaded. xmlHTTPRequests, intervals and timeouts are examples of asynchronous functions. Events are asynchronous too. But as you said, they are all built-in.

Can you make asynchronous operations yourself in javascript without the use of built in asynchronous operations like setTimeout()?

In the old days not so easy. As I said, you can make custom events and web workers. Nowadays:

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
  • https://davidwalsh.name/es6-generators/
like image 181
Mouser Avatar answered Oct 27 '25 22:10

Mouser