Take the following code for example,
Output
When looking at the output, it is understandable that the statements has been executing sequentially.
But if I do a modification to the code like the following, the output will be different.
Output:
Don't worry about the line number 6 yet. the amendment there will just delay the the execution of the statement "console.log('statement 01')" by 100 milliseconds.
Now the "statement 01" prints out at the end of the line. The change of the output can be explained as follows.
the JS interpreter sees the line 6 (which is the first line of the script), and realize that it has to wait for a 100 milliseconds before executing the statement "console.log('statement 01')", but sees that other four lines has no such delay and can be executed right away. So it goes ahead and execute the other four line "while waiting for" 100 milliseconds to elapse. Once the 100 milliseconds are up it executes the statement "console.log('statement 01')".
To see the effect more clearly just change the value to 1000, at line 6 and run again. like this,
"setTimeout(()=>{console.log('statement 01')}, 1000); "
NOTE: If you set the value to 0 at line 6, what would happen?. If you think since the value is 0 and the interpreter does not have to wait anymore, the statements will be executed sequentially just fine. But it will not. You can test it by placing the value 0 there and running the script. The reason for this is beyond the scope of this discussion, but will be addressed in a later post.
Now imagine that this statement is a read/write operation that takes time. So holding all the subsequent statements makes no sense, so this asynchronous behavior is useful.
But, what if you want something to happen sequentially? how can you force the JS interpreter to work sequentially? That is when you want a Callback
Lets take the same example. What if you want the "statement 01" to be printed first no matter how much time it takes to execute.
For that you can write a simple trick as follows.
Output:
Here you will experience a one second delay and statements print out sequentially.
The function at line 20 is the callback function. That means as the name implies, it is the function that should be called once the first line executes
Now the function at line 12 is expecting another function as the input argument. And that function is called right after the execution of the statement "console.log('statement 01')".
That whole block of code (line 14 and 15) is delayed by 1000 milliseconds.
At line 9, I am calling the function "executeInOrder" with the function "restOfTheStatements" as the callback.
This is a very simple example of a callback function, but I will do more deeper dives in the up coming posts.
Comments
Post a Comment