Underscore.js _.defer() Function
The _.defer() function is used to invoke/call a function until the current call stack is cleared. Its major advantage is that it performs expensive computations, calculations or HTML in chunks without blocking the UI threads from updating. It has similar functioning to setTimeOut() function with a delay of 0. The function which is passed to this function will be invoked first.
It takes two arguments:
- The function
- The arguments (optional)
It does not return any value rather it performs the function passed.
- Passing alert() function to the _.defer() function:
The _.defer() function first checks the current calling stack. If it is cleared then the alert() function passed will be performed and the string passed to it which is “This is the deferred function” will be displayed. But if the current calling stack is not cleared and has some other jobs to be performed then the alert() function will not be called immediately rather it needs to wait until the stack becomes empty.
- Performing addition using _.defer() function:
We can perform all kinds of mathematical operations using the _.defer() function. Like here we are performing addition of 7 and 3 and then alerting it. The same procedure will be followed. First, the current calling stack will be checked. If it is not empty then no other function will be called. But if it is all cleared then the alert function will be called displaying the addition of 7 and 3 which is 10.
- Passing console.log() function to the _.defer() function:
We can even use other functions like the console.log() function. The _.defer() function will check whether the calling stack is empty or not. If it is not empty then the console.log() function will not be called. Otherwise, “This is the deferred function” will be displayed on the console.
- Performing addition operation to the _.defer() function:
We can even perform addition operation to the console.log() function. Like here we are performing addition of 1000 and 5666. If the calling stack is empty then, “6666” (1000 + 5666) will be displayed otherwise no function will be called.
These commands will not work in Google console or in firefox as for these additional files need to be added which they didn’t have added.
So, add the given links to your HTML file and then run them.
The links are as follows: