JSFiddle - React, Tailwind, and code Playground

by Scott Kaye

JavaScript

var useAsync = true;

console.clear();

//Run fn in a worker thread, then call the callback with the returned result.
var async = function (fn, callback) {
    fn = fn.toString();

    var url = URL.createObjectURL(new Blob(
    ["var r=(", fn, ")();postMessage(r)"], {
        type: "application/javascript"
    }));

    var worker = new Worker(url);
    worker.onmessage = function (e) {
        callback(e.data);
    };

    URL.revokeObjectURL(url);
};


if (useAsync) {
    var result = async(function () {
        //Something that takes a long time to complete
        var i;
        for (i = 0; i < 1e9; ++i);
        return i;
    }, function (result) {
        console.log("Async", result);
    });
} else {
    //Something that takes a long time to complete
    var i;
    for (i = 0; i < 1e9; ++i);
    console.log("Sync", i);
}

for (var i = 0; i < 10; ++i) {
    setTimeout(function () {
        console.log(i);
    }, 200 * i);
};