【问题标题】:How can I stop async function on click event javascript?如何在单击事件 javascript 上停止异步功能?
【发布时间】:2021-10-07 09:06:02
【问题描述】:

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

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

【问题讨论】:

    标签: javascript asynchronous async-await dom-events async.js


    【解决方案1】:

    这样的?

    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>

    【讨论】:

      猜你喜欢
      • 2019-11-23
      • 2017-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多