ThreadJS Example 2

Simple job with with array iteration

HTML

<script src="https://cdn.rawgit.com/AshanFernando/ThreadJS/master/thread.min.js"></script>
<h2>Example 2:</h2>

<strong>Run the fiddle to compute the results ...</strong>

<p>Code segment 1 uses the main Thread to compute the summation of numbers from 1 - 2,000,000,000 and display the results.</p>
<p id='result_1'></p>
<p>Code segment 2 uses two parallel Threads to compute the same summation by dividing it to (1 - 1,000,000,000) and (1,000,000,001 - 2,000,000,000), displays the results.</p>
<p id='result_2'></p>
<p>Note: The difference due to large number addition</p>

JavaScript

/*Start: Code segment 1 */
var s1_start = new Date();
var x = 0;
for (var i = 1; i <= 2000000000; i++) {
    x = x + i;
}
var s1_end = new Date();
$('#result_1').text('Result 1: ' + x + ' ( ' + (s1_end - s1_start) + '  milliseconds)');

/*End: Code segment 1 */

/*Start: Code segment 2 */
var s2_start = new Date(),
    s2_end;
var y = 0;
var thread1 = new Thread();
thread1.start(null, function () {
    var x = 0;
    for (var i = 1; i <= 1000000000; i++) {
        x = x + i;
    }
    return x;
}).then(function (result) {
    y = y + result;
    s2_end = new Date();
    $('#result_2').text('Result 2: ' + y + ' ( ' + (s2_end - s2_start) + '  milliseconds)');
    this.close();
});

var thread2 = new Thread();
thread2.start(null, function () {
    var x = 0;
    for (var i = 1000000001; i <= 2000000000; i++) {
        x = x + i;
    }
    return x;
}).then(function (result) {
    y = y + result;
    s2_end = new Date();
    $('#result_2').text('Result 2: ' + y + ' ( ' + (s2_end - s2_start) + '  milliseconds)');
    this.close();
})

/*End: Code segment 2 */