什么是setTimeout(function(){// dostuff},0);实际上该怎么办? [英] What is setTimeout(function(){//dostuff}, 0); actually supposed to do?

查看:72
本文介绍了什么是setTimeout(function(){// dostuff},0);实际上该怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这种模式:

setTimeout(function(){
             // do stuff
}, 0);

实际上是从循环内向UI返回控制权?你应该什么时候使用它?它在所有浏览器中是否同样有效?

Actually return control to the UI from within a loop? When are you supposed to use it? Does it work equally well in all browsers?

推荐答案

它以异步方式运行代码(不是并行运行)。延迟通常更改为最小10毫秒,但这无关紧要。

It runs code asynchronously (not in parallel though). The delay is usually changed to a minimum of 10ms, but that doesn't matter.

此技巧的主要用途是避免限制调用堆栈深度。如果你冒险达到极限(走深树结构并计划在叶子上做很多工作),你可以使用超时来启动一个新的空调用堆栈。

The main use for this trick is to avoid limit of call stack depth. If you risk reaching limit (walk deep tree structure and plan to do a lot of work on leafs), you can use timeout to start function with a new, empty call stack.

您也可以使用它来避免阻塞当前线程。例如,如果您不希望< script> 元素延迟加载页面:

You can also use it to avoid blocking current thread. For example if you don't want <script> element to delay loading of a page:

<script>compute_last_pi_digit()</script> <!-- blocking -->

<script>setTimeout(compute_last_pi_digit,0)</script> <!-- non-blocking -->

这篇关于什么是setTimeout(function(){// dostuff},0);实际上该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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