我正在使用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
关于javascript - spin.js 在长时间运行的任务期间不会显示,但在我单步执行调试器时会显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26352074/