如何停止点击事件 javascript 的异步功能?

How can I stop async function on click event javascript?

我的异步函数和承诺在这里:

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();
}

我在 click 元素上调用了 bubblesort 函数,id 为 sort

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
}

现场直播link。您可以看到并且很容易理解我到底想要什么以及问题是什么。
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>