Home > OS >  what is the difference events and tasks?
what is the difference events and tasks?

Time:08-01

I am learning event loop, but I don't distinguish terminology about events and tasks.In the event loop context,I can understand "task" in MDN,

tasks are triggered by events.A task is any JavaScript code which is scheduled to be run by the standard mechanisms such as initially starting to run a program, an event callback being run, or an interval or timeout being fired.

Async Tasks are triggered by events. Can I understand that events are tasks that executed in another thread? what is event in the event loop?

CodePudding user response:

Events do not occur in the event loop. When an event is dispatched, the callback function that must be executed is pushed onto the macrotask queue. There is no designated place for events inside the event loop, since events are not functions themselves. (macrotask and task is the same thing)

To give you a concrete example, let's say you have a button and a user clicks that button. When the user clicks that button, the callback function that must be executed is pushed onto the macrotask queue and when the call stack is completely empty the event loop will push the callback function from the macrotask queue onto the call stack. There is also a microtask queue but I don't want to confuse you.

I suggest reading the following articles that perfectly describe the event loop in chrome and how it works:

CodePudding user response:

Look at this code

setTimeout( function () {
  console.log('hello');
}, 2000)

This will print hello to console after 2000 milliseconds.

In this snippet the anonymous function in which we're printing to console is the task.

Now think of an event as a signal, after 2 seconds, a signal is sent to the event loop, or in "event terminology" an event is fired or an event is triggered.

So the task is executed after it receives the signal (the event)!

CodePudding user response:

Events are signals that tell the event loop that a task is now ready to run. They are not part of the event loop, they come from outside. Examples are DOM events (such as clicks, keyboard events etc), network events (readystatechange, progress), timer events (from setTimeout). Events are not tasks themselves. They may or may not be fired by another thread - often enough, the event loop polls for them.

  • Related