我的异步函数和这里的承诺:
Sort.bubbleSort = function () {
const timer = (ms) => new Promise((res) => setTimeout(res, ms));
async function sort() {
for(){
// i want to delay for every loop that's why I used async function and
//promise and timer here.
await timer(time);
}
}
// calling async function here
sort();
}
我在带有 id sort 的 click 元素上调用了冒泡排序函数
document.getElementById("sort").addEventListener("click", Sort.bubbleSort);
于是函数开始执行。单击带有 id random-data 的元素后,我想停止该功能。
这里我需要解决方案:
document.getElementById("random-data").addEventListener("click", function () {
Sort.bubblesort().stop() // need to stop or pause
}
这是实时链接。你可以看到并很容易理解我到底想要什么以及有什么问题。
Live Demo Link | Github Repository link
答案 0 :(得分:2)
类似的东西?
const Sort = {
bubbleSort() {
const timer = (ms) => new Promise((res) => setTimeout(res, ms));
async function sort(self) {
for (let i = 0; i <= 100; i++) {
if (self.abort) {
self.abort = false;
return;
}
console.log(i);
await timer(1000);
}
}
sort(this);
},
bubbleSortStop() {
this.abort = true;
}
};
document.getElementById("sort")
.addEventListener("click", Sort.bubbleSort.bind(Sort));
document.getElementById("random-data")
.addEventListener("click", Sort.bubbleSortStop.bind(Sort));
<button id="sort">sort</button>
<button id="random-data">stop</button>