Generating a random number of progress bars I have this JSFiddle that generates a random number of progress bars then assigns a random number and percent to them.

I am wondering if you know how to better optimize this code to have better run-time.



/*Creates a random amount of bars*/

function runBars() {
    var start = new Date().getTime();
    /*Sets the maximuim amount of bars, 10 if NaN or less than 1*/
    var max_bars = parseInt($('#max_bars').val());
    if (isNaN(max_bars) || max_bars &lt; 1) {
        max_bars = 10;
    }
    /*Grabs a random number of bars*/
    var bars = getRandom(max_bars);
    /*clears bars container*/
    $('#bars-container').html('');
    /*Appends progress bars.*/
    for (var i = 0; i &lt; bars; i++) {
        var element = $('&lt;label&gt;Number ' + (i + 1) + '&lt;/label&gt;&lt;div class="progress"&gt;&lt;div class="progress-bar"&gt;&lt;/div&gt;&lt;/div&gt;');
        $('#bars-container').append(element);
    }
    var end = new Date().getTime();
    var time = end - start;
    $('#bar_time').text(time);
    $('#bar_amount').text(bars);
    /*Populates bars with percents*/
    runPercent();
}

/*Random int with max*/
function getRandom(max) {
    return Math.floor((Math.random() * max) + 1);
}

/*Gets percent based on maxium number, making the percent scale */
function getPercent(x, total, biggest) {
    return Math.floor(x / biggest * 100) + '%';
}

/*Populates percent in each progress bar*/
function runPercent() {
    var start = new Date().getTime();
    var length = $('.progress-bar').size();
    var data = [];
    var total = 0;
    var biggest = 0;
    /*pushes random ints to array*/
    for (var i = 0; i &lt; length; i++) {
        var temp = getRandom(50);
        data.push(temp);
        total += temp;
        if (biggest &lt; temp) {
            biggest = temp
        }
    }
    /*Each progress bar gets a width percentage and sets the text.*/
    $('.progress-bar').each(function (index) {
        $(this).width(getPercent(data[index], total, biggest));
        $(this).text(data[index] + ' / ' + total);
    });
    var end = new Date().getTime();
    var time = end - start;
    $('#percent_time').text(time);
}
/*handles button events*/
$('#percent').click(runPercent);
$('#bars').click(runBars);

/*initiates on page load*/
runBars();
.float {
    position:fixed;
    right:0px;
    text-align:right;
}
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;
&lt;script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"&gt;&lt;/script&gt;
&lt;link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/&gt;

&lt;div class='float'&gt;
    &lt;button id='percent'&gt;Randomize %&lt;/button&gt;
    &lt;button id='bars'&gt;Randomize Bars&lt;/button&gt;
    &lt;/br&gt;
    &lt;input id='max_bars' type='number' placeholder='Max Number of Bars' /&gt;
&lt;/div&gt;

&lt;h2&gt;Result: &lt;/h2&gt;

&lt;pre&gt;
Amount of Bars: &lt;span id='bar_amount'&gt;&lt;/span&gt;
    
In Miliseconds:
    
Bar Time:       &lt;span id='bar_time'&gt;&lt;/span&gt;
Percent Time:   &lt;span id='percent_time'&gt;&lt;/span&gt;
&lt;/pre&gt;

&lt;div id='bars-container'&gt;&lt;/div&gt;
1. Native methods will perform better than jQuery equivalents

Replacing jQuery calls with the native JavaScript equivalents where possible will improve performance. This will also increase the verbosity of your code, which may be undesirable, although arguably it can make the code more readable/less ambiguous.

Examples:



Use document.getElementById('ID') instead of $('#ID') when retrieving a single element by its ID
use document.querySelector('.className') instead of $('.className') when retrieving a single element by a CSS selector
Use document.querySelectorAll('.className') instead of $('.className') when retrieving an array of elements by a CSS selector
Use Element.innerHTML to update the text/html inside an element instead of using $(.cssSelector).html() or $(.cssSelector).text()
If you're only appending HTML to an element, use the more efficient Element.insertAdjacentHTML('beforeend',YourHTML) instead of modifying Element.innerHTML


2. Don't query the DOM for elements any more than you need to

In some cases your code selects an element multiple times. You can improve performance by selecting it once and saving it to a variable, then referencing that variable instead of selecting it again. Otherwise the JavaScript is forced to crawl the DOM multiple times to retrieve the same element.

Examples:


In the runBars() method, $('#bars-container') is called once to clear its HTML content, then again several times (once for every bar) to append more HTML to it. This is causing performance to degrade steeply as the number of bars increases.
Similarly, in the runPercent() method, the array of progress bars is selected via $('.progress-bar') once to get its length, then selected a second time to set the width and text of each progress bar.


3. Include a Radix parameter when calling parseInt()

This one is more of a minor nitpick: when calling parseInt() you should make it a habit to include a radix parameter indicating the base of the number in the string. 

Otherwise the browser will do its best to pick the right base system based on the string value... strings that start with '0x' will be considered hexadecimal, while strings that start with '0' will be considered octal, and any other strings will be considered decimals. 

Making a habit of passing 10 explicitly as your radix parameter will not only save the browser the tiny bit of effort it expends on checking for a string prefix, but it will save you from headaches if you ever find yourself parsing a string with a zero preceding a decimal number.

Example Code

Check out the performance of the code below, which has no jQuery dependencies except for the progress bar CSS:



/*Creates a random amount of bars*/

function runBars() {
    var start = new Date().getTime();
    /*Sets the maximuim amount of bars, 10 if NaN or less than 1*/
    var max_bars = parseInt(document.getElementById('max_bars').value, 10);
    if (isNaN(max_bars) || max_bars &lt; 1) {
        max_bars = 10;
    }
    /*Grabs a random number of bars*/
    var bars = getRandom(max_bars);
    /*clears bars container*/
    var container = document.getElementById('bars-container');
    container.innerHTML = '';
    /*Appends progress bars.*/
    for (var i = 0; i &lt; bars; i++) {
        container.insertAdjacentHTML('beforeEnd', '&lt;label&gt;Number ' + (i + 1) + '&lt;/label&gt;&lt;div class="progress"&gt;&lt;div class="progress-bar"&gt;&lt;/div&gt;&lt;/div&gt;');
    }
    var end = new Date().getTime();
    var time = end - start;
    document.getElementById('bar_time').innerHTML = time;
    document.getElementById('bar_amount').innerHTML = bars;
    /*Populates bars with percents*/
    runPercent();
}

/*Random int with max*/
function getRandom(max) {
    return Math.floor((Math.random() * max) + 1);
}

/*Gets percent based on maxium number, making the percent scale */
function getPercent(x, total, biggest) {
    return Math.floor(x / biggest * 100) + '%';
}

/*Populates percent in each progress bar*/
function runPercent() {
    var start = new Date().getTime();
    var progressBars = document.querySelectorAll(".progress-bar");
    var data = [];
    var total = 0;
    var biggest = 0;
    /*pushes random ints to array*/
    for (var i = 0; i &lt; progressBars.length; i++) {
        var temp = getRandom(50);
        data.push(temp);
        total += temp;
        if (biggest &lt; temp) {
            biggest = temp;
        }
    }
    /*Each progress bar gets a width percentage and sets the text.*/
    for (var index = 0; index &lt; progressBars.length; index++) {
        progressBars[index].style.width = getPercent(data[index], total, biggest);
        progressBars[index].innerHTML = data[index] + ' / ' + total;
    }
    var end = new Date().getTime();
    var time = end - start;
    document.getElementById('percent_time').innerHTML = time;
}
/*handles button events*/
var btnPercent = document.getElementById("percent");
var btnBars = document.getElementById("bars");
if (btnPercent.addEventListener) {
    btnPercent.addEventListener("click", runPercent);
    btnBars.addEventListener("click", runBars);
} else {
    btnPercent.attachEvent("onclick", runPercent);
    btnBars.attachEvent("onclick", runBars);
}

/*initiates on page load*/
runBars();
.float {
  position: fixed;
  right: 0px;
  text-align: right;
}
&lt;link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/&gt;
&lt;div class='float'&gt;
  &lt;button id='percent'&gt;Randomize %&lt;/button&gt;
  &lt;button id='bars'&gt;Randomize Bars&lt;/button&gt;
  &lt;/br&gt;
  &lt;input id='max_bars' type='number' placeholder='Max Number of Bars' /&gt;
&lt;/div&gt;

&lt;h2&gt;Result: &lt;/h2&gt;

&lt;pre&gt;
Amount of Bars: &lt;span id='bar_amount'&gt;&lt;/span&gt;
    
In Miliseconds:
    
Bar Time:       &lt;span id='bar_time'&gt;&lt;/span&gt;
Percent Time:   &lt;span id='percent_time'&gt;&lt;/span&gt;
&lt;/pre&gt;

&lt;div id='bars-container'&gt;&lt;/div&gt;