Skip to content

Instantly share code, notes, and snippets.

@maxmarinich
Last active December 5, 2022 13:28
Show Gist options
  • Save maxmarinich/9e2d9f0bd0fee52dece84251180b24e9 to your computer and use it in GitHub Desktop.
Save maxmarinich/9e2d9f0bd0fee52dece84251180b24e9 to your computer and use it in GitHub Desktop.
Non blocking thread calculation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Title</title>
</head>
<body>
<div style="display: inline-block">
<h3 id="sequence"></h3>
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="alert" onclick="onPause()">Pause</button>
</div>
<div>
<progress max="" value="" id="progress" style="width: 140px"></progress>
Result: <span id="result">0</span>
</div>
<script>
const start = document.getElementById("start");
const stop = document.getElementById("stop");
const result = document.getElementById("result");
const progress = document.getElementById("progress");
const sequence = document.getElementById("sequence");
start.onclick = () => onStart();
stop.onclick = () => onStop();
let sum = 0;
let startTime, timer;
const items = 100_000_000;
const chunk = Math.min(1_000_000, items);
const sequenceSum = (items * (items + 1)) / 2;
const hasSequence = Number.MAX_SAFE_INTEGER > sequenceSum;
if (hasSequence) {
sequence.innerText = `Sequence sum of "${items}"`;
progress.max = sequenceSum / chunk;
} else {
sequence.innerText = `Sequence sum if "${sequenceSum}" out of MAX_SAFE_INTEGER_NUMBER`;
}
function time() {
return (performance.now() - startTime) / 1000 + " sec.";
}
function onStart() {
sum = 0;
progress.value = 0;
result.innerText = 0;
if (!hasSequence) return;
if (!startTime) startTime = performance.now();
count(0, chunk);
}
function count(from, to) {
for (let i = from; i <= to; i++) {
sum += i;
}
result.innerText = sum;
progress.value = sum / chunk;
if (to < items) {
const start = to + 1;
const end = to + chunk <= items ? to + chunk : items;
timer = setTimeout(() => count(start, end), 10);
} else {
sum = 0;
startTime = 0;
}
}
function onStop() {
startTime = 0;
clearTimeout(timer);
}
function onPause() {
if (startTime) alert("Paused");
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment