简体   繁体   中英

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

So what I am trying to do is to stop a function after a number of seconds in a game. i have a basic function that increases a score in a game.

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

I use this code numerous times throughout my game for example two circles. Red circle......

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

and Green circle.....

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

What i am trying to do is to stop this increase functions from incrementing the score after a certain number of seconds on both circles. I have tried setTimeout below increments after the score after 4 seconds

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

and clearTimeout wont allow the score to increment at all

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

and setInterval().Is my thought process wrong? thanks in advance

If the function is running in a loop it could check inside the loop how long it is running and break the loop if it is running too long. If the function is called in a loop from outside, the calling code could do the same check. The caller can remember the time it started calling the function and compare with the current time.

var timeStarted = new Date();

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

It seems you not using the clearTimeout function as should.

in order to use the clearTimeout you need to get first the return object from the setTimeout function.

Here is code example:

var myVar;

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

function myStopFunction() {
  clearTimeout(myVar);
}

Please take a look in w3schools how to use these functions or on MDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM