簡體   English   中英

幾秒鍾后如何停止運行功能? setTimeout,clearTimeout和setInterval無法正常工作

[英]How to stop a function running after a number of seconds? setTimeout, clearTimeout and setInterval wont work correctly

所以我想做的是在游戲中幾秒鍾后停止某個功能。 我有一項基本功能,可以提高游戲的得分。

      function increaseScore() {
            score = score + 1; // increase score
            display_score.innerHTML = "score is " + score;  // prints new score
        }

我在整個游戲中多次使用此代碼,例如兩個圈子。 紅色圓圈……

  if(red_circle == 0) {//stop the incrementing the clicker
      increaseScore();
      red_circle = 1;}

和綠色圓圈.....

         if(green_circle == 0) {//stop the incrementing the clicker
       increaseScore();
          green_circle = 1;}

我想做的是在兩個圓圈上經過一定的秒數后,停止這種增加分數的遞增功能。 我嘗試了setTimeout在4秒后得分之后以增量遞增

 if(red_circle == 0) {//stop the incrementing the clicker
    setTimeout(function() { increaseScore();  
    red_circle = 1;
}, 4000);
}

和clearTimeout根本不允許分數增加

 if(green_circle == 0) {//stop the incrementing the clicker
    clearTimeout(function() { increaseScore();  
    green_circle = 1;
     }, 3000);
    }

和setInterval()。我的思維過程是否錯誤? 提前致謝

如果函數在循環中運行,則可以在循環內部檢查其運行時間,如果運行時間過長,則可以中斷循環。 如果從外部在循環中調用該函數,則調用代碼可以執行相同的檢查。 調用者可以記住它開始調用該函數的時間,並與當前時間進行比較。

var timeStarted = new Date();

// in the loop:
var currentTime = new Date();
if ((currentTime - timeStarted) < 4 * 1000)
{
  // call the function
}

看來您沒有按需使用clearTimeout函數。

為了使用clearTimeout,您需要首先從setTimeout函數中獲取返回對象。

這是代碼示例:

var myVar;

function myFunction() {
  myVar = setTimeout(function(){ alert("Hello"); }, 3000);
}

function myStopFunction() {
  clearTimeout(myVar);
}

請在w3schools中看看如何使用這些功能或在MDN上

暫無
暫無

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

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