在繁忙的 JavaScript 代码期间页面未更新
我有一个很长的 JavaScript 脚本。问题是在中间我想改变一个div的innerHtml来表示“快完成了,请稍候”。我认为问题是我调用了 jquery 函数。在函数的成功回调中,我调用另一个函数,这是我尝试更新页面的地方。
如果我使用 firebug 设置断点并单步执行代码,页面就会更新并且我会看到 div 的消息。但如果我只是让代码运行,我就看不到该消息。如果我在更新 div 之前和之后设置一个警报框,我也会看到它。
有人见过这样的事情吗?
谢谢你!
I have a pretty long javascript script. The problem is that in the middle of it I want to change a div's innerHtml to say "almost done please wait". I think the issue is that I call a jquery function. The in the success callback of the function I call another function which is where I am trying to update the page from.
If I set a breakpoint using firebug and step through the code, the page updates and I see the div's message. But if I just let the code run, I don't see the message. If I set an alert box before and after updating the div I see it too.
Anyone seen something like this before?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常,当 JS 代码运行时,所有其他渲染都会停止,就像您所看到的那样。您可以尝试使用 setTimeout 函数来允许在页面上进行渲染,如下所示:
请注意,doMoreStuff 是另一个函数,它将执行处理的最后部分。
如果你的代码可以这样分割,它将允许浏览器进入一些渲染周期。您可能想要尝试延迟(上面的 50)来找到适合您的数字,但如果您只想设置 div 的内容,那么 50 应该没问题(甚至可能 0 也可以)。
另外,我不记得设置 innerHTML 的 jQuery 语法,但我认为这一点很容易理解:)
Typically when JS code is being run all other rendering is halted, just like what you're seeing. You can try to use the setTimeout function to allow rendering to occur on your page like so:
Note that doMoreStuff is another function that will do the last part of your processing.
If your code can be split up this way it will allow the browser to get in some render cycles. You might want to experiment with the delay (50 above) to find a number that works for you, but if all you want to do is set the content of a div then 50 should be ok (possibly even 0 will work).
Also, I can't remember the jQuery syntax for setting innerHTML but I think the point gets across :)