Why is underscore delaying fix so many of my problems?

After using the backbone for several weeks, I realized that the underscore ended up eliminating many of the asynchrony issues I ran into regarding various kinds of rendering. Can someone please help me understand what the underscore deterrent does and how it differs from $ .ready () or another type of wait for functions to display. What are the downsides of its use?

_.defer = function(func) { return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); }; 
+44
Mar 18 '13 at 23:57
source share
1 answer
 # These are equivalent _.defer(fn); setTimeout(fn, 1); 

So defer is just a millisecond of setTimeout . (He got some more convenient features, but they are not important here.)




JavaScript works with loops. It is single-threaded, but its start starts and stops based on events or timers. Each time your JS engine runs some code, it starts one iteration of the run loop.

So, what defer means, says: "Run this code in the next loop of the loop."

 _.defer(function() { alert('after'); }); alert('before'); 

This is a warning before and then after. This is due to the fact that the current cycle of the cycle completes which warnings are โ€œbeforeโ€, and then a new start cycle starts immediately and runs the code โ€œafterโ€.

So anytime you have the code right here, but you want it to run the code that comes up after that code, then you would use defer .

 _.defer(functionToRunLast); functionToRunFirst(); 

This can be convenient with the DOM. Sometimes you change it, but the changes are not analyzed and are not displayed immediately. At the end of the startup cycle, the browser catches up and analyzes and displays the DOM, then the next startup cycle starts and can interact with the newly created DOM.

(Exactly which scripts cause the DOM to delay, I'm not sure, but in the past I noticed this in my own projects.)




This is NOT a replacement for the DOM. The next run cycle may occur before the DOM is ready to go, do not confuse these concepts.

+71
Mar 19 '13 at 0:10
source share



All Articles