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 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用