Examples of callback functions in JS and js callback Functions
This article describes the callback functions in JS. We will share this with you for your reference. The details are as follows:
Before talking about the callback function, let's take a look at a piece of code. I believe that students with some js basics can understand its meaning:
Document. getElementById ('Demo'). click = function () {alert (1 );};
This code is actually an Event Callback, so the write is actually relatively vague. Let's take a look at the following code.
Document. getElementById ('Demo'). addEventListener ('click', function () {alert (1 )});
The two pieces of code actually do the same thing. The difference is just the difference in writing. Let's look at thisAddEventListener ('eventname', callback)
,AddEventListener
This function has two parameters. The first parameter is the event name, and the second parameter is actually the callback function. according to the method described in the book, the parameters in the function can be variables, it can also be a function. It may be said that the function is still awesome. Let's look at the following example.
Function demo (a, B, callback) {let c = a + B; callback (c) ;}; demo (1, 2, function (c) {alert (c ); // 3 })
This Code defines a demo function, which has three parameters a, B, and callback. We declare a local variable c in this function, then execute our callback (callback function), and then execute the demo function.
The three parameters of this function are as follows: 3 is displayed in the return function. This is a simple callback function. To really understand the meaning of the callback function, I think it is still to understand its purpose. Only by understanding its purpose can we really understand it.
The most common application scenario of callback functions is asynchronous operations. Because asynchronous operations do not know when the operation will end, the code we execute in the future cannot proceed according to the proper process.