如何告诉javascript立即更新DOM? [英] How do I tell javascript to immediately update the DOM?

查看:185
本文介绍了如何告诉javascript立即更新DOM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



HTML:

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

Javascript:

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

函数tellViewerLoading(){
//告诉用户发生加载。
foo.innerHTML ='loading ...';
}

函数someActionThatTakesALongTime(){
//做一些需要很长时间的动作。
var i = 0;
while(i< 100000){i ++;的console.log(I);};
}

函数domUpdateDelayExperiment(){
tellViewerLoading();
someActionThatTakesALongTime();
}

domUpdateDelayExperiment();

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



我想要发生的是为了立即更新DOM tellViewerLoading()被调用。



相反,发生的是DOM似乎在 someActionThatTakesALongTime()完成运行。在这一点上,显示一个加载消息是无用的。



如何在 tellViewerLoading()被调用?

解决方案

使用setTimeout生成长时间运行的函数:

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

说明: tellViewerLoading()函数更新DOM,但浏览器不会反映屏幕,直到 domUpdateDelayExperiment()返回。通过使用setTimeout()延迟 someActionThatTakesALongTime ,我们让浏览器反映DOM更改。超时是任意的,但其最小值在某些浏览器中可能很重要。 50 ms的值是足够公平的。


I am trying to load a 'loading' message to the user before a time-intensive function is called in javascript.

HTML:

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

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/

What I want to happen is for the DOM to be updated immediately after tellViewerLoading() is called.

Instead, what happens is that the DOM seems to be updated after someActionThatTakesALongTime() finishes running. 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?

解决方案

Spawn the long-time running function with 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. By delaying someActionThatTakesALongTime by means of setTimeout() we let the browser to reflect DOM changes. The timeout is arbitrary, but its minimum value may be important in some browsers. A value of 50 ms is fair enough.

这篇关于如何告诉javascript立即更新DOM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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