Skip to content

Commit

Permalink
Split buttons, try using visibility API and AbortController
Browse files Browse the repository at this point in the history
  • Loading branch information
shawyu-okta committed Oct 30, 2024
1 parent 2c289d3 commit 0538baf
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
3 changes: 2 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
</head>
<body>
<h1>Hello world</h1>
<button onclick="main()">GO</button>
<button onclick="main(false)">GO</button>
<button onclick="main(true)">GO (with experiment)</button>
<div id="output"></div>
</body>
</html>
33 changes: 28 additions & 5 deletions script.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,35 @@
const originalTime = new Date().getTime();
let lastTime = originalTime;
const abortController = new AbortController();
const abortSignal = abortController.signal;
let timeout;

const main = () => {
const main = (useExperiment = false) => {
if (useExperiment) {
document.addEventListener("visibilitychange", () => {
if (document.hidden) {
if (timeout) {
clearTimeout(timeout);
}
abortController.abort("Document was hidden, aborting request");
} else {
console.warn("Document is visible again, re-attempting request");
timeout = setTimeout(makeRequest, 2000);
}
});
}
let requestCount = 0;
const outputElement = document.getElementById("output");
const makeRequest = async () => {
const url = "https://httpbin.org/post";
const response = await fetch(url, { mode: "cors", method: "post" });
const options = {
mode: "cors",
method: "post",
}
if (useExperiment) {
options.signal = abortSignal;
}
const response = await fetch(url, options);
const time = new Date().getTime();

if (response.ok) {
Expand All @@ -19,16 +42,16 @@ const main = () => {
newLine.appendChild(newContent);

lastTime = time;
setTimeout(makeRequest, 2000);
timeout = setTimeout(makeRequest, 2000);
outputElement.appendChild(newLine);
} else {
lastTime = time;
setTimeout(makeRequest, 2000);
timeout = setTimeout(makeRequest, 2000);
throw new Error('HTTP error! Status: ' + response.status);
}
};

setTimeout(() => {
timeout = setTimeout(() => {
makeRequest();
}, 2000);
};

0 comments on commit 0538baf

Please sign in to comment.