Chunking Example

by James Hughes

HTML

<h2>Asynchronous Processing</h2>
<a href="javascript:;" onclick="doProcessing(complete); return false;" class="button">Process</a>
<div id="progress-meter" class="status_msg">Ready</div>
Test Input: <input type="text"/>

CSS

body {
    font-family: Verdana;
  }
  .button {
    border: 1px solid black;
    background: #fff;
    padding: 5px;
    color: black;
    text-decoration: none;
  }
  .button:hover{
    background: #ddd;
  }
  .status_msg {
    color: #999;
    margin-top: 0.5em;
    font-size: 18pt;
  }
  h2 {
    margin-bottom: 10px;
  }

JavaScript

(function(){
  function complete(){
    alert("Processing Complete");
  }

  function doProcessing(callback){

    var el = document.getElementById("progress-meter");
    el.innerHTML = "Processing";

    /* setup iteration */
    var iterations = 99999999;
    var chunks = iterations/100;  /* each chunk is 1% of the overal processing count*/
    var i=0;

    /* self executing anonymous function */
    (function() {

      /* process chunk */
      for(var count = 0;i<iterations;i++) {
        var j = Math.round(Math.sqrt(i));
        count++;
        if(count == 99999)
          break;
      }

      /* more to process */
      if(i<iterations){
        /* update screen */
        el.innerHTML = Math.round((i/iterations)*100) + '% Complete';

        /* recurse for next segment */
        setTimeout(arguments.callee,0);
      }else{
        /* update screen */
        el.innerHTML = "Done!";

        /* call optional callback */
        if(callback){ callback() }
      }
    })();
  }

  window.doProcessing = doProcessing;
    window.complete = complete;
}());