简体   繁体   English

如何强制浏览器重绘并避免UI更新延迟?

[英]How to force browser repaint and avoid UI update delay?

I need the browser to update my UI before a long(er) operation is done. 在完成较长的操作之前,我需要浏览器更新UI。 Currently the browser is waiting until after everything is complete and then updating the UI, which means UI freezes for 1-2 seconds then updates. 当前,浏览器正在等待所有操作完成之后再更新UI,这意味着UI冻结1-2秒然后更新。

So, user clicks button in UI, then this code executes: 因此,用户单击UI中的按钮,然后执行以下代码:

$('#mybutton').click(function(e) {

e.preventDefault();// prevent the default anchor functionality

$('#mainctrldiv').css('display', 'none');
$('#otherctrldiv').css('display', 'block');

var img = $('<img id="spareimg" style="display:none;">');
img.attr('src', canvas.getActiveObject().toDataURL()); // This is causing the delay!
img.appendTo('body');
}

It's the canvas.getActiveObject().toDataURL() (a FabricJS function) that is taking the time. canvas.getActiveObject().toDataURL()的是canvas.getActiveObject().toDataURL() (一个FabricJS函数)。 I want this to happen after the 2 divs have been visibly displayed to the user, to they don't notice. 我希望这在将2个div明显显示给用户之后发生,因为他们没有注意到。 Need this to work in all commonly used browsers out there! 需要它才能在所有常用的浏览器中正常工作! (mobile as well as desktop). (移动设备和台式机)。

Research suggested that reading the css display properties immediately after setting them would force the browser to repaint so I added in the following code straight after setting these properties but the delay still occurred: 研究表明,在设置css显示属性后立即读取它们会迫使浏览器重新绘制,因此我在设置这些属性后立即添加了以下代码,但仍然发生了延迟:

$('#mainctrldiv').css('display');
$('#otherctrldiv').css('display');

Many thanks for any suggestions! 非常感谢您的任何建议!

Try using setTimeout with zero delay , it will push these to the end of the thread. 尝试使用具有零延迟的 setTimeout ,它将把它们推送到线程的末尾。 You can also try adding some delay if zero delay doesn't work for you. 如果零延迟不适合您,您还可以尝试添加一些延迟。 But I am not sure if that exact line is causing the issue, if it is post another question on how to optimise and decrease the time. 但是,我不确定该确切的线是否会引起此问题,是否发布另一个有关如何优化和减少时间的问题。

$('#mybutton').click(function(e) {
  e.preventDefault(); // prevent the default anchor functionality
  $('#mainctrldiv').css('display', 'none');
  $('#otherctrldiv').css('display', 'block');
  setTimeout(function() {
    var img = $('<img id="spareimg" style="display:none;">');
    img.attr('src', canvas.getActiveObject().toDataURL()); // This is causing the delay!
    img.appendTo('body');
  }, 0);
}

It's important to note that the function or code snippet cannot be executed until the thread that called setTimeout() has terminated. 重要的是要注意,在调用setTimeout()的线程终止之前,函数或代码段无法执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM