Javascript 同步调用与更新

Javascript syncronous call with update

本文关键字:更新 调用 同步 Javascript      更新时间:2023-09-26

我有一个执行长任务的函数。我想创建一个能够通知调用方进度的函数。最终,我想使用当前进度更新 UI。

像这样:

function myLongMethod(progressCallback)
{
    for(var i = 0 ... )
    {
        progressCallback(i) ;
    }
}

这有效,但 UI 上的更新并不流畅。有没有更好的方法?我更喜欢使用 deferred.notify() 的 jquery 延迟对象的东西。有什么想法吗?

你的代码很好。你还有另一个问题。Javscript 始终在 UI 线程上运行。您的操作正在阻止此线程(浏览器),您将看到浏览器窗口受到一些阻塞。幸运的是,在现代浏览器中实现了一种称为 Web Worker 的解决方法。很简单,只需在主脚本中调用另一个脚本,然后执行该脚本:

var w = new Worker("another_script.js");

如果工作人员已准备就绪,您可以通过向工作人员添加事件列表器来对结果做出反应:

w.onmessage = function(event) {
  //do something
}

使用此模式时,UI 不会阻止。您甚至可以从 Web 工作者返回数据,并将脚本包含在其中。您可以在此处找到更多详细信息,这是一个很好的入门教程。

嗨,

您可以将缓动效果应用于您的 UI 以提高流畅性,我给出了以下代码,它可能会对您有所帮助

var oldProgress = 0;
var uiUpdater = null;
function updateUI(newProgress){         
    if(uiUpdater !=null){
        // update your ui to the old progress first
        window.clearInterval(uiUpdater); // clearing the previous timer
    }        
    var diff = newProgress - oldProgress;
    oldProgress = newProgress;
    var stepSize = diff/5; // applying the new change in 5 steps to the UI
    uiUpdater = window.setInterVal(function(){
       // updating your UI after every 100 milliseconds
       // to give the smoothness
       diff -= stepSize; // decreasing the difference gradually
       if(diff<=0){
           window.clearInterval(uiUpdater); // clearing the interval once the update is done
       } 
    },100);
}

您必须从具有新进度的回调中调用"updateUI"方法。