You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

setInterval仅执行一次函数问题求助

问题:setInterval仅执行一次目标函数

我希望按住HTML按钮时,每500ms执行一次moveActualCam函数,但当前代码中setInterval只执行了一次该函数,相关代码如下:

目标执行函数

function moveActualCam(where) {
  console.log("Called");
  seq_json = {
    direzione: where,
  };
  async function postData() {
    const url = "fetchcammove";

    const response = await fetch(url, {
      method: "POST",
      headers: {
        "X-CSRFToken": csrftoken,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(seq_json),
    });
    return await response.json();
  }
  postData().then((data) => {
    console.log("OK");
  });
}

HTML按钮调用

<button
  onmousedown="moveCam('LEFT');"
  onmouseup="stopMoveCam();"
  type="button"
  class="btn btn-secondary"
>

当前JavaScript控制代码

<script>
  const csrftoken = document.querySelector("[name=csrfmiddlewaretoken]").value;
  function moveActualCam(where) {
    console.log("Called");
    seq_json = {
      direzione: where,
    };
    async function postData() {
      const url = "fetchcammove";

      const response = await fetch(url, {
        method: "POST",
        headers: {
          "X-CSRFToken": csrftoken,
          "Content-Type": "application/json",
        },
        body: JSON.stringify(seq_json),
      });
      return await response.json();
    }
    postData().then((data) => {
      console.log("OK");
    });
  }

  function moveCam(where) {
    intervalCam = setInterval(moveActualCam(where), 500);
  }

  function stopMoveCam() {
    clearInterval(intervalCam);
  }
</script>

问题原因

setInterval的第一个参数需要传入函数引用,而你当前写的moveActualCam(where)是直接执行了函数,把函数的返回值(此处为undefined)传给了setInterval,因此只会在调用moveCam时执行一次函数,之后不会重复触发。

修复方案

方案1:使用匿名函数包裹调用

修改moveCam函数,用箭头函数包裹目标函数调用,确保传递给setInterval的是一个函数引用:

function moveCam(where) {
  intervalCam = setInterval(() => moveActualCam(where), 500);
}

方案2:使用bind绑定参数

通过bind把参数绑定到目标函数上,生成带参数的新函数引用传给setInterval:

function moveCam(where) {
  intervalCam = setInterval(moveActualCam.bind(null, where), 500);
}

额外优化:避免全局变量污染

建议把intervalCam用let声明在脚本顶部,避免成为全局变量:

<script>
  const csrftoken = document.querySelector("[name=csrfmiddlewaretoken]").value;
  let intervalCam; // 声明局部变量

  // ... 其他函数代码不变

  function moveCam(where) {
    intervalCam = setInterval(() => moveActualCam(where), 500);
  }

  function stopMoveCam() {
    clearInterval(intervalCam);
  }
</script>

内容的提问来源于stack exchange,提问作者NicoCaldo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 00:26:39