Source Code

for file S01_AsyncSamples/CalcFactorsAsync2.htm

<!DOCTYPE html>
<html lang="en">
<head>
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  <title>Prime factors calculator</title>
</head>
<body>
  <h1>Prime factors calculator</h1>
  <table>
    <tbody>
      <tr>
        <th><label for="inputField">Please enter a number:</label></th>
        <td><input id="inputField" onkeyup="StartCalcPrimeFactors()"></td>
      </tr>
      <tr>
        <th><label>The factors are:</label></th>
        <td><input id="outputField" size="60" disabled="disabled"></td>
      </tr>
    </tbody>
  </table>
  <h3>Hint:</h3>
  <p>try 12313123123123 or 12313123123123123123 for long running calculations ! </p>

  <script type="text/javascript">
    
var _num = "";
var _timer = null;

var prime;  // try this factor (only primes will match!)
var number; // product of the remaining factors
var outputText;

function StartCalcPrimeFactors() {
  var inputText = document.getElementById("inputField").value;
  if (_num != inputText) {
    if (_timer != null)
      window.clearTimeout(_timer);
    document.getElementById("outputField").value = "wait...";
    _num = inputText;
    
    prime = 2; // start with 2
    number = parseInt(inputText);
    outputText = "";

    _timer = window.setTimeout("CalcPrimeFactors()", 50, "javascript");
  } // if
} // StartCalcPrimeFactors


// calc prime factors
function CalcPrimeFactors() {
  _timer = null;

  if (number == 1) {
    // finished. all factors found
    outputText = outputText + " finished.";
    document.getElementById("outputField").value = outputText;

  } else if (prime * prime > number) {
    // the last factor (a prime) is here.
    outputText = outputText + " " + number + " finished.";
    document.getElementById("outputField").value = outputText;

  } else {
    // Debug: window.status = prime;

    if (number % prime != 0) {
      // try the next factor (a little bit faster)
      prime += (prime == 2 ? 1 : 2);
      
    } else {
      // found a factor !
      outputText = outputText + " " + prime;
      document.getElementById("outputField").value = outputText;
      number = number / prime;
    } // if
    _timer = window.setTimeout(CalcPrimeFactors, 0, "javascript");
  } // if

} // CalcPrimeFactors

    </script>

  <hr />
  <p>This sample uses HTML and Javascript asynchronously.</p>
  <p>The long running calculation is spitted into multiple parts and gets slowly.</p>
  <p>Benefit: There is no blocking of the UI any more.</p>
  <p>This page is part of the <a href="http://ajaxaspects.blogspot.com/">http://ajaxaspects.blogspot.com/</a>
    project.</p>
  <hr />
</body>
</html>


This page is part of the http://www.mathertel.de/ web site.

For updates and discussions see http://ajaxaspects.blogspot.com/.