在执行Javascript函数期间更新DOM [英] Updating DOM during Javascript function execution

查看:42
本文介绍了在执行Javascript函数期间更新DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个运行很长时间的Javascript函数,如下所示:

I have a long running Javascript function, that looks like this:

window.myFunction = function() {
    for(var i=0;i<500;i++){
        // calling a function here
        document.getElementbyID('mySpan').innerHTML = "Completed step " + i + "/500"
    }
}

我的函数经常调用另一个同步函数(在此示例中,我使用了500),并且在用户等待任务完成时,我想实现类似加载栏的功能,但是我通过更新跨度来演示了该功能.我的情况在这里.每次更新跨度时是否可以强制进行某种形式的DOM刷新?

My function calls another synchronous function very often (I used 500 in this example) and while the user waits for the task to complete, i'd like to implement something like a loading bar but I demonstrated it with updating a span in my case here. Is it possible to force a DOM refresh of some sort every time I update my span?

推荐答案

由于脚本在浏览器中的单个线程中运行,因此像您这样的任何方法都需要在更新DOM之前完成.但是,您可以做的是使用迭代功能,并稍加延迟,以允许浏览器重绘.

Since scripts run in a single thread in your browser, any method like yours will need to complete before the DOM is updated. What you can do, however, is use an iterative function with a small delay that allows the browser to redraw.

这是一个例子...

window.myFunction = function(i) {
    // calling a function here - passing i as a parameter, if needed
    document.getElementById('mySpan').innerHTML = "Completed step " + i + "/500";
    i++;
    if (i <= 500) setTimeout(function() { myFunction(i) }, 1);
}

myFunction(0);

<span id="mySpan"></span>

这篇关于在执行Javascript函数期间更新DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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