Skip to content

Instantly share code, notes, and snippets.

@elierotenberg
Created October 22, 2018 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elierotenberg/687c44f035f136d092edcbf9d2078a7c to your computer and use it in GitHub Desktop.
Save elierotenberg/687c44f035f136d092edcbf9d2078a7c to your computer and use it in GitHub Desktop.
concurrency.js
const state = {
counter: 0
};
const randomInt = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;
const sleep = (min, max = min) =>
new Promise(resolve => {
setTimeout(resolve, randomInt(min, max));
});
const incrementCounter = () => {
const currentCounter = state.counter;
sleep(1000, 2000).then(() => {
state.counter = currentCounter + 1;
});
};
incrementCounter();
incrementCounter();
sleep(3000).then(() => console.log(state.counter)); // aléatoirement 1 ou 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment