JSFiddle - React, Tailwind, and code Playground

by Spencer Evans

HTML

<!-- Load Thread.js library -->
<script src="http://spencer-evans.com/share/github/threadjs/fiddle/thread.js"></script>

<!-- Add a page header -->
<h1 style="margin-bottom: 5px;">Thread.js - Ping Example</h1>
<p id="unsupported" style="display: none; background-color: rgba(255,180, 180,1); padding: 10px; border-radius: 6px;">Your browser does not support javascript workers or threadjs.</p>
<p id="error" style="display: none; background-color: rgba(255,180, 180,1); padding: 10px; border-radius: 6px;">ERROR: While Thread.js supports IE10, this example will only work on IE11 or newer. This is because the thread.js library is being loaded from an external domain, which is unsupported in IE10.</p>

<div id="container">
    <p style="margin-left: 10px; margin-right: 20px; margin-bottom: 20px; color: rgba(0,0,0,0.75);">
        This is a <a href="https://github.com/swevans/thread.js">Thread.js multi-threaded javascript</a> example. You can find more information out about the library <a href="https://github.com/swevans/thread.js">here</a>.<br/>
        <br/>
        This example sends a ping event from the main UI thread to a background thread. The background thread then sends back a pong event along with some text containing its threadID.</p>
    
    <!-- Set up a place for output -->
    <strong>Output:</strong>
    <div id="output" style="padding-left: 20px;">Sending ping to thread...<br/></div>
</div>

JavaScript

// Grab a reference to the ouput
var output = document.getElementById("output");

/** Defines the code that will run in the thread. */
function threadCode()
{
    /** Handles ping events sent to the thead. */
    function pingHandler(evt) 
    {
        // Send back a pong
        Thread.parent.postEvent("pong", "Hi from thread " + Thread.threadID);
    }
    
    // Watch for ping events from the parent
    Thread.parent.addEventListener("ping", pingHandler);
}

/**
 * Will run in Main window context to handle pong events from the child thread. 
 */
function pongHandler(evt) 
{
	output.innerHTML += "Received pong from thread! <br/>";
    output.innerHTML += " Got message: " + evt.data + "<br/>";
}

// Wrap thread creation in some checks and error handling for purposes of this demo
// Create a new thread, watch for events from it, and add code to it
if (threadjs.isSupported)
{
    // Create a thread and run the code
    try
    {
        var myThread = new Thread(threadCode);

        // Watch for a pong event, and send a ping event
        myThread.addEventListener("pong", pongHandler);
        myThread.postEvent("ping");
    }
    catch(err)
    {
        document.getElementById("error").style.display = "block";
        document.getElementById("container").style.display = "none";
    }
}
else
{
	document.getElementById("unsupported").style.display = "block";
    document.getElementById("container").style.display = "none";
}