簡體   English   中英

clearInterval() 似乎沒有按預期工作

[英]clearInterval() does not seem to work as expected

我正在開發一個 JavaScript/WebRTC 對講機應用程序,需要按住一個按鈕才能發送音頻。 它工作正常,直到我在按住左鍵的同時單擊鼠標右鍵,這導致setInterval function 繼續工作並且clearInterval無法通過其 ID 停止它。 它只是永遠持續下去。 根據我讀過的所有內容, clearInterval應該停止它,尤其是在全局設置間隔的情況下。

var intervalId;

$("#transmitbutton").on("mousedown touchstart", function () {
    intervalId = setInterval(function () {
        console.log("PTT pressed");
    }, 1000);
});

$("#transmitcontainer").on("mouseup touchend mouseleave", function () {
    clearInterval(intervalId);
});

我試過啟動和停止按鈕,結果相同。 clearInterval不起作用。

var intervalId;

$("#transmitstart").on("click", function () {
    intervalId = setInterval(function () {
        console.log("PTT pressed");
    }, 1000);
});

$("#transmitstop").on("click", function () {
    clearInterval(intervalId);
});   

如果您碰巧多次調用創建它的 function,您將有一個不可取消的間隔,因為您將覆蓋間隔 ID。 所以要么你需要取消它,要么不做一個新的間隔。

var intervalId;

$("#transmitbutton").on('mousedown touchstart', function() {
  if (intervalId) return; // either exit out and not create a new one
  // if (intervalId) clearInterval(intervalId);  //or remove it here
  intervalId = setInterval(function(){
    console.log("PTT pressed");
  }, 1000);
});

$("#transmitcontainer").on('mouseup touchend mouseleave', function() {
  if (intervalId) clearInterval(intervalId);
  intervalId = null;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM