创建加载屏幕以进行长时间计算 [英] Create an loading screen for long calculation

查看:43
本文介绍了创建加载屏幕以进行长时间计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要进行大量计算.因此,我将此处引用为创建一个简单的加载屏幕.不幸的是,计算完成后会显示加载屏幕.

I need to perform a huge calculation. So, I refer here to create a simple loading screen. Unfortunately, the loading screen is shown after the calculation complete.

这是我的代码

class RosterScheduler
{
   .........................
   autoAssign()
   {
    var startDate=parseInt($("#autoPlannStartDate").val());
    var endDate=parseInt($("#autoPlanEndDate").val());
    $("body").addClass("loading");
    if (startDate>endDate)
        alert("Invalid start date or end date selection");
    else
    {   
        if (this.rosterTable.haveInvalidPreferredShift(startDate,endDate))
            alert("Invalid shift requirement detected");
        else
        {
            var self=this;
            var finalRoster;
            var roster,tempAverageSD,lowestAverageSD=100.0;

            this.theLowestSDRosters=[];
            this.theLowestMissingShiftRosters=[];
            for (var i=0;i<100;i++)
            {   
                this._genRoster(startDate,endDate);
            }
            console.log("Done");
        }
    }   
   } 
}

我发现,如果我标记了for循环,则加载屏幕正常工作.如果取消注释for循环,则在控制台中显示完成"后,将显示加载屏幕.我该如何解决该问题?我试图将函数_genRoster转换为Promise函数,但是它不起作用.

I found that if I remark the for loop, the loading screen working properly. If I uncomment the for loop, the loading screen is shown after the "Done" is shown in the console. How can I fix the problem? I have tried to convert the function _genRoster into a Promise function, however, it does not work.

推荐答案

看起来 _genRoster 正在阻止浏览器,并且没有提供任何资源来重新渲染/repaint,直到循环完成.一种可能是在之后运行循环,使浏览器有几毫秒的时间来呈现 .loading :

It looks like _genRoster is blocking the browser, and not giving it any resources to re-render/repaint until the loop is completed. One possibility would be to run the loop after giving the browser a few ms to render the .loading:

this.theLowestSDRosters = [];
this.theLowestMissingShiftRosters = [];
setTimeout(() => {
  for (var i = 0; i < 100; i++) {
    this._genRoster(startDate, endDate);
  }
  console.log("Done");
}, 50);

在单个 requestAnimationFrame 之后调用超时为0的函数可能更优雅,从而使浏览器有时间重绘,然后立即运行重循环:

It might be more elegant to call a function with 0 timeout after a single requestAnimationFrame, thus giving the browser time to repaint and then running the heavy loop immediately afterwards:

(警告:以下代码会阻塞您的浏览器一段时间)

(warning: the following code will block your browser for a bit)

document.body.style.backgroundColor = 'green';
window.requestAnimationFrame(() => {
  console.log('start, setting timeout');
  setTimeout(() => {
    for (let i = 0; i < 1000000000; i++) {
    }
    console.log('done');
  });
});

这篇关于创建加载屏幕以进行长时间计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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