I am using this snippet of code
let submitBtn,
stopBtn,
firstStepInput,
lastStepInput,
output = 0,
stopOutput = 0;
document.addEventListener("DOMContentLoaded", () => {
submitBtn = document.querySelector('#submit');
stopBtn = document.querySelector('#stop');
firstStepInput = document.querySelector('#firstStep');
lastStepInput = document.querySelector('#lastStep');
output = document.querySelector('#output');
stopOutput = document.querySelector('#stopOutput');
submitBtn.addEventListener('click', getValueInputs);
stopBtn.addEventListener('click', getValueStopOutput);
})
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const getValueInputs = () => {
let firstInputValoue = +firstStepInput.value || 0;
let lastInputValoue = +lastStepInput.value || 100;
for (let i = firstInputValoue; i <= lastInputValoue; i++) {
sleep(i * 1000).then(_ => {
output.innerHTML = i;
})
}
}
const getValueStopOutput = () => {
stopOutput.innerHTML = output.innerHTML;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div>
<div class="ms-3">
<div class="d-flex align-items-center mt-3">
<div>
<label for="firstStep">firstStep</label>
<input id="firstStep" type="number" class="form-control" />
</div>
<span class="mx-3">to</span>
<div>
<label for="lastStep">lastStep</label>
<input id="lastStep" type="number" class="form-control" />
</div>
</div>
<div class="mt-3 mx-auto">
<button id="submit" class="btn btn-sm btn-primary">Submit</button>
<button id="stop" class="btn btn-sm btn-info">Stop</button>
</div>
<div class="mt-3">
<p id="output"></p>
</div>
<div class="mt-3">
<p id="stopOutput"></p>
</div>
</div>
</div>
And with the help of this link, I was able to make a sleep function And it works perfectly
Now I have a problem that I can't stop and disable!
Now, for example, we put the number 0 in the input firstStep And in input lastStep for example 100 or more In this case, it takes 100 seconds for this function to finish Now my question is, in the meantime, if the user wants to stop the function altogether or enter new numbers, what should I do?