weixin_33749131 2020-04-06 02:05 采纳率: 0%
浏览 70

事件停止重复

I have a web app with the following HTML line:

<select id="dropdown"; onchange="update()">

and the associated JS is:

function update()
{
    val = document.getElementById("dropdown").value;
    arr = some_dict[val];
    CHUNK_SIZE = 1024;
    i = 0;

    function recursive_call()
    {
        data = arr.slice(CHUNK_SIZE*i, CHUNK_SIZE*i + CHUNK_SIZE);
        if (data.length < CHUNK_SIZE){return;}
        ...
        $.ajax({
            type: "POST",
            url: "/page",
            data: {"data": data},
            async: true,
            success: function (d){
                setTimeout(another_func, 3000);
                recursive_call();
            }
        })
        i++;
    }

}

Essentially, whenever a new dropdown value is selected, I recursively extract consecutive chunks from an array and send them to my server. When the array length is less than the chunk size, I return, stopping this process.

The issue is when a new dropdown value is selected and the recursion is incomplete. I would like to stop the existing recurring loop when a new value is selected, and beginning recurring for a new array associated with the new value.

I have tried a few things but the code is super messy and would further convolute what I have described here.

  • 写回答

1条回答

  • weixin_33726313 2020-04-06 02:21
    关注

    Here's an example of similar functionality using intervals instead of recursion.

    The benefit of this is you can cancel an interval with clearInterval

    let intervalReference = null
    let counter = 0
    
    function update() {
       counter = 0
       if(intervalReference !== null){
            clearInterval(intervalReference)
       }
      
      intervalReference = setInterval(()=>{
        counter++
        console.log(counter)
            //do your ajax in here
      }, 1000)
    }
    <select id="dropdown" onchange="update()">
     <option value="a">A</option>
      <option value="b">B</option>
    </select>

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?