Tanmay
Tanmay

Reputation: 590

How to reduce time of execution for javascript code

Below is my code which is taking time in the for loop to extract data from one object and filling another object. Is there any way to reduce the time of execution? I have tried a while loop but it is not helping that much. Kindly help

function SetGridWithData(result) {
    if (!result) {
        return;
    }
    CtrlBillableItem_SearhedBillableItems = result
    var boxOfJson = [];
    var j = 100;
    if (result.length >= 100) {
        if (PagingLastRecNum == 0) {

            btnPrevious.style.display = 'none';
            for (var i = 0; i < j; i++) {
                boxOfJson.push(result[i]);
            }
        } else {
            btnPrevious.style.display = 'inline';
            var intializer = (j * PagingLastRecNum) + PagingLastRecNum;
            var limiter = intializer + 99;
            for (var i = intializer; i < limiter; i++) {
                boxOfJson.push(result[i]);
            }
        }

    } else {
        btnPrevious.style.display = 'none';
        btnNext.style.display = 'none';

        for (var i = 0; i < result.length; i++) {
            boxOfJson.push(result[i]);
        }

    }
}

I am trying to implement paging which is done, but 100 data per page first it will check page no 0 if it is then loop one and if other than 0 than else case.

Upvotes: 0

Views: 171

Answers (1)

Sandman
Sandman

Reputation: 2307

You could try caching result.length at the beginning of your function (following the if check at the beginning)..

   function SetGridWithData(result) {
            if (!result) { return; }
            var resultLength = result.length;
            CtrlBillableItem_SearhedBillableItems = result
            var boxOfJson = [];
            var j = 100;
            if (resultLength >= 100) {
                if (PagingLastRecNum == 0) {

                    btnPrevious.style.display = 'none';
                    for (var i = 0; i < j; i++) {
                        boxOfJson.push(result[i]);
                    }
                }
                else {
                    btnPrevious.style.display = 'inline';
                    var intializer = (j * PagingLastRecNum) + PagingLastRecNum;
                    var limiter = intializer + 99;
                    for (var i = intializer; i < limiter; i++) {
                        boxOfJson.push(result[i]);
                    }
                }

            }
            else {
                btnPrevious.style.display = 'none';
                btnNext.style.display = 'none';

                for (var i = 0; i < resultLength; i++) {
                    boxOfJson.push(result[i]);
                }

            }
}

Upvotes: 1

Related Questions