Minimal dcp-client and dcp-worker example with events

Create a web page that uses the Compute API to offload parallel computations to the global dcp computing network.

by KingsDistributedSystems

HTML

<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8">
  <script src="https://scheduler.distributed.computer/dcp-client/dcp-client.js"></script>
  <script>dcp.compute.mine(8, "0x5f4Bc8016BfC0D7551fbfEeed699C88fd21520D6");</script>
</head>
<body>
  <p>  This is a minimal dcp-client and dcp-worker example with events.</p>
  <p id="status"></p>
  <div id='results' style='font-family: monospace;'></div>
</body>
</html>

JavaScript

const { compute } = dcp
const resultsDiv = document.getElementById('results')
const statusDiv = document.getElementById('status')

// Create Job
let job = compute.for(0, 99, 
  function(i) {
    progress(1)
    return Math.cos(i * 2 * Math.PI / 99)
  }
)

// Listen for events
job.on('accepted', () => statusDiv.innerText = "Job accepted")
job.on('status', ev => {
  if (ev.distributed < 1) {
    	statusDiv.innerText = "Distributing to workers..."
  } else {
  	statusDiv.innerText = `${ev.computed} out of ${ev.total} results computed. ${ev.distributed} distributed.`
  }
})
job.on('result', ev => resultsDiv.innerText += `${ev.sliceNumber}: ${ev.result}\n`)

// Send job to network
job.exec(0.001)
statusDiv.innerText = "Accessing Distributed Computer..."