我试图在javascript中调用耗时的函数之前向用户加载"加载"消息.
HTML:
<p id='foo'>Foo</p>?
Run Code Online (Sandbox Code Playgroud)
使用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();
Run Code Online (Sandbox Code Playgroud)
JSFiddle:http://jsfiddle.net/johnhoffman/xDRVF/
我想要发生的tellViewerLoading()是调用后立即更新DOM .
相反,发生的事情是DOM似乎在someActionThatTakesALongTime()完成运行后更新.此时,显示加载消息是没用的.
如何告诉javascript在tellViewerLoading()调用后立即更新DOM ?
使用setTimeout生成长时间运行函数:
function domUpdateDelayExperiment() {
tellViewerLoading();
setTimeout(someActionThatTakesALongTime, 50);
}
Run Code Online (Sandbox Code Playgroud)
说明:该tellViewerLoading()函数更新DOM,但浏览器在domUpdateDelayExperiment()返回之前不会反映屏幕上的更改.通过someActionThatTakesALongTimesetTimeout()延迟,我们让浏览器反映DOM的变化.超时是任意的,但在某些浏览器中,其最小值可能很重要.50毫秒的值是公平的.