Simple Callback function

Here is a simple Callback function.
callback function

2022-05-03_10h38_46

How does javascript execute task 2 before task 1. Since , as it is said javascript is sequential shouldnt task one be executed then delayed for 2 seconds and then task two be executed? Thanks for help.

First of all, please don’t post pictures of code - just post the code.

Task one gets executed second because you told it to.

The line:

setTimeout(taskOne, 2000);

tells JS, “after 2 seconds, run this function”.

JS does not wait. Some languages will wait for that to finish before moving on. They are synchronous languages with blocking code.

But a lot of JS is asynchronous. That is on purpose, since JS was developed for the web. There are a lot of things you have to wait for, loading data, images, etc. So, JS usually doesn’t wait. When you call setTimeout you was saying “run this function after this amount of time, but don’t wait”. In JS, you almost never “wait”. There are different ways to deal with this. The most basic level is callback functions. Then you’ll learn about Promises. Then you get to async/await, which is the closest you get to “waiting”. There are also generator functions which are used for things like Redux Saga.

1 Like

A lots of thanks for your tip and your understandable explanation. Gracias

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.