Skip to content

Instantly share code, notes, and snippets.

@ahmedsakr
Last active August 13, 2020 22:56
Show Gist options
  • Save ahmedsakr/8c44f72faca2847ee407015f6f0e8cfb to your computer and use it in GitHub Desktop.
Save ahmedsakr/8c44f72faca2847ee407015f6f0e8cfb to your computer and use it in GitHub Desktop.
A synchronized solution to the Ordered Server Counter Example
import { Mutex } from 'async-mutex';
import material from 'materialize-css/dist/js/materialize';
let count = 0;
let clientLock = new Mutex();
// Server Simulation
function processCommand() {
count += 1;
return count;
}
// Network Delay Simulation
async function serverDelay() {
return new Promise(resolve => setTimeout(resolve, parseInt(Math.random() * 500)));
}
window.addEventListener('load', () => {
document.getElementById("genToast").addEventListener('click', async () => {
let release = await clientLock.acquire();
await serverDelay();
let number = processCommand()
await serverDelay();
material.toast({
html: `<span style="font-size: 48px; padding: 2rem;">#${number}</span>`,
displayLength: 1000
});
release();
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment