如何在每次在循环内调用applet方法时进行进度条更新(不仅在循环完成时)?

问题描述:

我在调用applet方法后试图用jquery更新进度条时出现问题。我将文件复制到调用小程序方法的移动设备。除了进度条更新以外的所有内容似乎都能正常工作如何在每次在循环内调用applet方法时进行进度条更新(不仅在循环完成时)?

这些文件的副本在所有浏览器中都能正常工作,但只有在firefox中,每次applet方法完成后,进度条才会更新。其他浏览器在所有工作完成后都会更新进度条(循环结束)。

这是我的进度条代码:

<div class="progress progress-striped active" id="progress_bar"> 
    <div class="bar" id="progress-bar-count" style="width: 0%;">0%</div> 
</div> 

这是我的JavaScript逻辑(在Firefox工作完美):

var totalSize=0; 
var currTotalSize=0; 
//files infos 
totalSize=getXMLData(xml,'XML.FILES-SIZE'); 
var files = getXMLData(xml,'XML.FILES.FILE.FILE-PATH'); 
var filesSizes = getXMLData(xml,'XML.FILES.FILE.FILE-SIZE'); 
for(var index=0; index<files.length && status==true; index++){ 
    var appletReturn = $("#applet")[0].copyFiles(files[index]); 
    if(appletReturn=="true"){ 
    currTotalSize+=parseInt(filesSizes[index]); 
    var percentage=calcPercentage(currTotalSize, totalSize); //simple rule of 3 
    $('#progress-bar-count').text(percentage+'%'); 
    $('#progress-bar-count').css('width', percentage+'%'); 
    } 
    else{ 
    status=false; 
    } 
} 

你能helpe我做的JavaScript调用之前的进度条进行更新小程序的方法呢?

谢谢。

一个解决方案它把工作放在一个异步函数中。它只会在当前工作完成时循环。理论上这应该起作用。

jQuery的

$(document).ready(function() { 

    /// the Assync function. 

    var asyncFor = function(params) { 

     var defaults = { 
      total: 0, 
      limit: 1, 
      pause: 10, 
      context: this 
     }, 
      options = $.extend(defaults, params), 
      def = $.Deferred(), 
      step = 0, 
      done = 0; 

     this.loop = function() { 
      if (done < options.total) { 
      step = 0; 
      for (; step < options.limit; step += 1, done += 1) { 
       def.notifyWith(options.context, [done]); 
      } 
      setTimeout.apply(this, [this.loop, options.pause]); 
      } else { 
      def.resolveWith(options.context); 
      } 
     }; 

     setTimeout.apply(this, [this.loop, options.pause]); 
     return def; 
     }; 



    /// You do your work here 

var totalSize=0; 
var currTotalSize=0; 
//files infos 
totalSize=getXMLData(xml,'XML.FILES-SIZE'); 
var files = getXMLData(xml,'XML.FILES.FILE.FILE-PATH'); 
var filesSizes = getXMLData(xml,'XML.FILES.FILE.FILE-SIZE'); 

    asyncFor({ 
     total: files.length, 
     context: this 
    }).progress(function(step) { 

    var appletReturn = $("#applet")[0].copyFiles(files[step]); 

    currTotalSize+=parseInt(filesSizes[step]); 

    var percentage=calcPercentage(currTotalSize, totalSize); 

    $('#progress-bar-count').text(percentage+'%'); 

    $('#progress-bar-count').css('width', percentage+'%'); 

    }).done(function() { 

    alert("finished") 

    }); 

    }); 

基本演示

http://jsfiddle.net/3686gthy/

+0

谢谢!如果applet返回错误,我该如何中断这个执行?步骤=总计 – Bagata 2014-09-22 17:23:21

+1

虽然它的运行,如果你想在任何时候停止它(total == null) - http://jsfiddle.net/kagpe8u9/ – Tasos 2014-09-22 17:57:13

+0

工程就像一个魅力,但为什么* total == null *而不仅仅是*总= NULL *? – Bagata 2014-09-22 18:49:16