简体   繁体   English

如何告诉javascript立即更新DOM?

[英]How do I tell javascript to immediately update the DOM?

I am trying to load a 'loading' message to the user before a time-intensive function is called in javascript. 我试图在javascript中调用耗时的函数之前向用户加载“加载”消息。

HTML: HTML:

<p id='foo'>Foo</p>​

Javascript: 使用Javascript:

var foo = document.getElementById('foo');

function tellViewerLoading() {
  // Tell the user that loading is occuring.
  foo.innerHTML = 'loading...';   
}

function someActionThatTakesALongTime() {
  // Do some action that takes a long time.
  var i = 0;
  while(i < 100000) {i++; console.log(i);};
}

function domUpdateDelayExperiment() {
  tellViewerLoading();
  someActionThatTakesALongTime();
}

domUpdateDelayExperiment();

JSFiddle: http://jsfiddle.net/johnhoffman/xDRVF/ JSFiddle: http//jsfiddle.net/johnhoffman/xDRVF/

What I want to happen is for the DOM to be updated immediately after tellViewerLoading() is called. 我想要发生的是在tellViewerLoading()之后立即更新DOM。

Instead, what happens is that the DOM seems to be updated after someActionThatTakesALongTime() finishes running. 相反,发生的事情是DOM似乎在someActionThatTakesALongTime()完成运行后更新。 At that point, it is useless to display a loading message. 此时,显示加载消息是没用的。

How do I tell javascript to immediately update the DOM after tellViewerLoading() is called? 如何在tellViewerLoading()后告诉javascript立即更新DOM?

Spawn the long-time running function with setTimeout: 使用setTimeout生成长时间运行函数:

function domUpdateDelayExperiment() {
  tellViewerLoading();
  setTimeout(someActionThatTakesALongTime, 50);
}

Explanation: the tellViewerLoading() function updates the DOM but the browser won't reflect changes on screen until domUpdateDelayExperiment() returns. 说明: tellViewerLoading()函数更新DOM,但在domUpdateDelayExperiment()返回之前,浏览器不会反映屏幕上的更改。 By delaying someActionThatTakesALongTime by means of setTimeout() we let the browser to reflect DOM changes. 通过setTimeout()延迟someActionThatTakesALongTime ,我们让浏览器反映DOM的变化。 The timeout is arbitrary, but its minimum value may be important in some browsers. 超时是任意的,但在某些浏览器中,其最小值可能很重要。 A value of 50 ms is fair enough. 50毫秒的值是公平的。

Actually, if you step through your code using a debugger, you will see that the loading text is changed before the next function is called. 实际上,如果您使用调试器单步调试代码,您将看到在调用下一个函数之前更改了加载文本。

Your browser is just hanging at the long function call, so it can't change the displayed text. 您的浏览器只是挂在长函数调用上,因此无法更改显示的文本。

Using a short timeout can help if you want your browser to have enough time to change the display before going to the next function. 如果您希望浏览器在进入下一个功能之前有足够的时间更改显示,则使用短暂超时可能会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM