timeTaken(func)

Returns the time taken to execute a code-block in milliseconds.
Just enclose the code-block in a function, and pass the function to timeTaken.

Syntax

                
    function hello(){
        console.log("Hello World");
    }
    
    timeTaken(hello);              //returns the time taken to execute the function hello()  
            

Example

Left half of the canvas is filled with rectangles of magenta color made using iteration of nested for loops and right half is filled with rectangle of violet color made using iteration of nested while loops. and text displays the time taken by both the loops to execute.

Time taken can vary even in every page refresh.

                
    function lefthalf(){
        for(i=0;i<WIDTH/2;i+=5){
            for(j=0;j<HEIGHT;j+=5){
                new rect(i,j,5,5,'#f0f',1,'#f0f',0.5);
            }
        }
    }

    function righthalf(){
        i=WIDTH/2;
        while(i<WIDTH){
            j=0;    
            while(j<HEIGHT){
                new rect(i,j,5,5,'#82AAFF',1,'#82AAFF',0.5);
                j+=5;
            }
            i+=5;
        }
        
    }

    function draw(){
        
        lefthalf();
        righthalf();
        tl=timeTaken(lefthalf);
        tr=timeTaken(righthalf);
        new text(WIDTH/4,HEIGHT/2,"for loops: "+tl+"ms",16,'Inter',400,'#000',0,'#000','middle');
        new text(WIDTH/4*3,HEIGHT/2,"while loops: "+tr+"ms",16,'Inter',400,'#000',0,'#000','middle');
        
    }
    draw()