spin.js没有'它不会在长时间运行的任务中显示,但当我逐步通过调试器时会显示

spin.js doesn't show up during long running task, but does when I step through the debugger

本文关键字:显示 调试器 没有 js spin 运行 长时间 任务      更新时间:2023-09-26

我在一个长时间运行的处理任务中使用spin.js。

当我刚运行任务时,在任务运行之前所做的UI更改不会在任务本身中显示。但是,当我使用调试器手动完成整个过程时,UI会按预期进行更新。什么东西?我试着在长时间运行的函数上运行setTimeout,给UI更新的时间;没有骰子。

function updateGraphDisplay() {
    var opts = {
        lines: 13, // The number of lines to draw
        length: 20, // The length of each line
        width: 10, // The line thickness
        radius: 30, // The radius of the inner circle
        corners: 1, // Corner roundness (0..1)
        rotate: 0, // The rotation offset
        direction: 1, // 1: clockwise, -1: counterclockwise
        color: '#000', // #rgb or #rrggbb or array of colors
        speed: 1, // Rounds per second
        trail: 60, // Afterglow percentage
        shadow: false, // Whether to render a shadow
        hwaccel: false, // Whether to use hardware acceleration
        className: 'spinner', // The CSS class to assign to the spinner
        zIndex: 2e9, // The z-index (defaults to 2000000000)
        top: '50%', // Top position relative to parent
        left: '50%' // Left position relative to parent
    };
    var spinner = new Spinner(opts).spin();
    $('#chart').append(spinner.el);
    // long running local computations (~4s)
    Highcharts.charts[0].series[0].setData(sentimentDataPoints);
    Highcharts.charts[0].series[1].setData(volumeDataPoints);
    spinner.stop();
}

您必须记住JS是单线程的。当您使用setTimeout(fn, delay)时,JS会将函数fn排队,以便在未来运行大约delay毫秒,然后继续运行setTimeout()之后的行。

这意味着你的updateGraphDisplay()函数将运行到完成,包括创建微调器,然后在几毫秒后删除它。因此,你没有看到它更新。

相反,您需要做的是将"长时间运行的本地计算"之后的所有内容移动到传递给setTimeout()的函数中,这样它将在未来代码运行后执行

缩写代码结构示例:

 // initialisation code
 // create spinner and append to DOM
 setTimeout(function () {
     // do calculations
     // update graph
     // clear spinner
 }, 0); // even a delay of 0 will work