JSFiddle - React, Tailwind, and code Playground

by thegje

JavaScript

/* this is non commented version, have a look and see below commented version to see what's going on, press cntrl+enter to run script */

$(document).ready(function () {
    
    $("body").append("<div id='draw'></div>");

    colors = ["#ff0000", "#00ff00", "#0000ff"];
    
    i = 0; 
    function drawing() {
        if (i < 100) {
            r = Math.floor((Math.random() * 3));  
            $("#draw").prepend("<div style='width:4px;height:4px;margin:2px;background:"+colors[r]+"'></div>"); 
        } else { //
            alert("Finished"); 
            clearInterval(refreshIntervalId); 
        }
        i++;
    }
   
    var refreshIntervalId = setInterval(drawing, 50);
    

});


/* commented version: */

$(document).ready(function () {
    
    // Add an element to the page that we will use to draw inside
    $("body").append("<div id='draw'></div>");
    
    // Define Red Green and Blue in hex codes***
    colors = ["#ff0000", "#00ff00", "#0000ff"];
    
    // Create drawing function
    i = 0; // Make the variable i = 0
    function drawing() {
        if (i < 100) { // if i is less than 100
            r = Math.floor((Math.random() * 3));  // make r = a random number from 0 - 2 (0,1,2)
            $("#draw").prepend("<div style='width:4px;height:4px;margin:2px;background:"+colors[r]+"'></div>"); // add elemen to drawing space with background equal to colors[r], this is the colors variable we defined above*** and we access one of the values in it with the 'r' which has been randomly assigned the value of either 0, 1 or 2, returning #ff0000, #00ff00, or #0000ff.
        } else { // if i is equal to or more than 100
            alert("Finished"); // alert finished
            clearInterval(refreshIntervalId); // stop running
        }
        i++; // increase the value of i
    }
   
    // Create variable that runs the drawing function every 50 milliseconds
    var refreshIntervalId = setInterval(drawing, 50);
    
});