Set a Promise and await till the runtime.
const start = document.getElementById("start");
const bar = document.getElementById("bar");
const percent = document.getElementById("percent");
const results = document.getElementById("results");
let promisseId = 0;
const counter = (n = 100) => {
if (n > 100) {
n = 100;
}
promisseId++;
return new Promise((resolve) => {
// Here you can set a reject, (resolve, reject) the reject() must run in case your counter throws an error...
const id = promisseId;
let i = 1; // i is set outsite.
const interval = setInterval(function() {
if (i === n) {
clearInterval(interval);
resolve({
i,
id
});
}
bar.value = i++;
}, 100);
});
};
start.addEventListener(
"click",
() =>
counter(parseInt(this.percent.value)).then((res) => {
const p = document.createElement("p");
p.innerText = `Promise ${res.id} resolved! It goes to ${res.i}%`;
results.appendChild(p);
})
); // console.log the "res" when its resolved! You can use another value instead of 100 at counter(100).
<input id="bar" type="range" min="1" max="100" value="1" /> Go to <input id="percent" type="number" value="100" />% |
<button id="start">Start</button>
<p>Run it multiple times and simultaneously w/ different values, to see the magic!</p>
<div id="results"></div>
On the above example try Starting an 100% execution and imediatly an 10%, you will see the execution of 10% ending before the full one.
Just to make it complete, this will be a case using both, resolve and reject:
new Promise((resolve, reject) => {
if (yourCondition) {
resolve('Something to return as Success');
} else {
reject('Something to return on Failed');
}
});