我的异步功能和承诺如下:
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排序的click元素上调用bubblesort函数。
document.getElementById("sort").addEventListener("click", Sort.bubbleSort);所以函数开始执行。在单击带有id随机数据的元素后,我希望停止该函数。
在这里我需要解决办法:
document.getElementById("random-data").addEventListener("click", function () {
Sort.bubblesort().stop() // need to stop or pause
}这是现场链接。你可以很容易地理解我到底想要什么,问题是什么。
发布于 2021-08-01 22:37:26
像这样吗?
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>
https://stackoverflow.com/questions/68614344
复制相似问题