为什么强调延迟解决这么多的问题,我? [英] why does underscore defer fix so many of my issues?

查看:89
本文介绍了为什么强调延迟解决这么多的问题,我?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用主干我已经意识到了几个星期的下划线延迟结束了固定许多我跑进渲染方面各种意见异步问题之后。
是否有人可以帮助我了解什么突出延迟做,以及如何对DOM渲染它的功能是不同的$。就绪()或其他类型的等待。什么是使用它的两边下来?

  _。推迟=功能(FUNC){
    返回_.delay.apply(_,[FUNC,1] .concat(slice.call(参数,1)));
};


解决方案

 #这些相当于
_.defer(FN);
的setTimeout(FN,1);

所以延迟简直就是一毫秒的setTimeout 。的(它有一些更多的便利功能,但这些都并不重要。)


JavaScript的已经用完循环。它是单线程的,但其执行的启动和停止基于事件或计时器。每次您JS引擎踢上运行一些code,它开始其运行循环的一次迭代。

那么延迟确实是说:在接下来的运行循环运行此code。

  _推迟(函数(){警报(后);});
警报('前');

此警报,然后之后之前。这是因为当前运行的循环结束它提醒之前,然后右键后新的运行循环开始并运行code之后的警报。

所以,任何时候你有code就在这里,但你希望它运行code此code后先发生,那么你可以使用延迟

  _推迟(functionToRunLast);
functionToRunFirst();

这是很方便的与DOM。有时候,你改变它,但是改变不会解析或立即呈现。在运行循环结束时,浏览器赶上并解析并呈现DOM中,然后在下一个运行循环开始,并可以用新呈现的DOM交互。

(究竟是什么情形造成这种延迟DOM解析,我不知道,但我过去在我自己的项目注意到了这一点。)


这是的的DOM的准备好替换。接下来的运行循环可能发生的的DOM准备过火灾,不要混淆这些概念。

After using backbone for a couple of weeks I have realized that underscore defer ended up fixing many of the async issues I ran into regarding rendering various views. Can someone please help me understand exactly what underscore defer does and how is it different that $.ready() or other type of wait for dom to render functions. What are the down sides of using it ?

_.defer = function(func) {
    return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};

解决方案

# These are equivalent
_.defer(fn);
setTimeout(fn, 1);

So defer is simply a one millisecond setTimeout. (It's got a few more convenience features but those aren't important here.)


JavaScript has run loops. It's single threaded, but its execution starts and stops based on events or timers. Each time your JS engine kicks on to run some code, it's starting one iteration of its run loop.

So what defer does is say "run this code in the next run loop".

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

This alerts "before" and then "after". This is because the the current run loop concludes which alerts "before", and then right afterward a new run loop starts and runs the code the alerts "after".

So anytime you have code right here, but you want it to run code which occurs after this code first, then you would use defer.

_.defer(functionToRunLast);
functionToRunFirst();

This can be handy with the DOM. Sometimes you change it, but the changes don't parse or render immediately. At the end of the run loop, the browser catches up and parses and renders the DOM, then the next run loop starts and can interact with the newly rendered DOM.

(Exactly what scenarios cause this delayed DOM parse, I'm not sure, but I've noticed it in my own projects in the past.)


It is NOT a replacement for DOM ready. The next run loop may happen before DOM ready ever fires, don't confuse these concepts.

这篇关于为什么强调延迟解决这么多的问题,我?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆