Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain how Meteor.defer() works?

Tags:

meteor

So... Meteor.defer(function(){ // stuff }) isn't in the docs:

https://github.com/meteor/meteor/issues/2176

But this links seems to say that it's simply equivalent to

Meteor.setTimeout(function(){ // stuff }, 0);

If that's the case, how does this do, um, anything? It's basically saying "wait for 0 ms and then run the function".

So... it runs the function instantly.

What am I missing here? Is this kind of like Tracker.afterFlush or something? Does it somehow wait for "things" (what kind of things?) to finish before running?

like image 877
fuzzybabybunny Avatar asked Jul 23 '15 05:07

fuzzybabybunny


1 Answers

I see Meteor.defer() a lot on SO being used as a bit of a hack on added helper methods to run after the dom is (somewhat) loaded - basically to get the same effect as running code inside of a Template.foo.rendered method.

However, the main (and best) use of Meteor.defer is to run a task asynchronously.

Let's say we have an app where we are sending an email. On the server, it may take several seconds for that to process inside of a meteor method, slowing down your application drastically. However, if you wrap that process in a Meteor.defer the email processing won't block execution, the email still sends (when it gets a chance, not instantly), but everything runs much faster, since the code that follows isn't waiting. There is a great example lesson about deferring execution at Bulletproof Meteor.

You can actually get the same effect with a setTimeout(f,0) - if you have a slow function, you could wrap it in the setTimeout and the rest of the code will complete, and 'defer' the slow process in the timeout, so although it doesn't seem like it, setTimeout(f,0) does actually have a pretty useful purpose!

To see an example of this in action, here's a fiddle, open the console and watch where 'foo' logs.

like image 68
Jordan Davis Avatar answered Nov 07 '22 21:11

Jordan Davis