gpt4 book ai didi

javascript - 如何在单击事件 javascript 上停止异步功能?

转载 作者:行者123 更新时间:2023-12-04 07:19:12 24 4
gpt4 key购买 nike

我的异步功能和 promise 在这里:

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 随机数据的元素后,我想停止该功能。
在这里我需要解决方案:
document.getElementById("random-data").addEventListener("click", function () {
Sort.bubblesort().stop() // need to stop or pause
}
这是实时链接。你可以看到并很容易理解我到底想要什么以及有什么问题。
Live Demo Link | Github Repository link

最佳答案

像这样的东西?

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>

关于javascript - 如何在单击事件 javascript 上停止异步功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68614344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com