Home > Blockchain >  how to execute code 3 seconds later once executed in a infinite loop
how to execute code 3 seconds later once executed in a infinite loop

Time:04-20

I am making a game using html canvas in which i want to check for certain condition every time in animate loop and if that condition become true once then I don't want to check for next 3 seconds and after 3 seconds i want to check again. Like

function animate(){
  requestAnimationFrame(animate)
  if (checking something){
    if this if statement gets executed then don't check this if statement for next 3 seconds 
  }

This might sound bit confusing but is there anyway to do this.

CodePudding user response:

My suggestion would be to add a flag - another variable that you can use to check if an operation should be done, and another function that'll toggle the flag after a certain amount of time.

// THE CHECKING FLAG
let shouldCheckCondition = true;

function animate(){
  requestAnimationFrame(animate)
  
  // CHECK THE FLAG FIRST, IF SHOULD NOT CHECK, EXIT THE FUNCTION
  if (!shouldCheckCondition) return;

  if (condition){
    // DISABLE THE CHECKING FLAG SO YOU SKIP THE SUBSEQUENT CHECKS
    shouldCheckCondition = false;

    // DO SOMETHING WHEN CONDITION IS MET AND CHECKING SHOULD BE DONE

    // ENABLE THE CHECKING FLAG AFTER 3 second
    setTimeout(() => { shouldCheckCondition = true; }, 3000);
  }

CodePudding user response:

If you want to do it inline within another method, setInterval might not help.

You can just make a note of the last time you did that check (eg. system time in milliseconds) and then make sure that it is more than 3000ms after that when you next do the check.

date.valueOf(); //An existing date object to milliseconds format
(new Date()).valueOf(); //current time in ms

You can have two vars lastCheckedTime and currentTime.

CodePudding user response:

requestAnimationFrame tries to run on the next frame, not after three seconds. So don't use requestAnimationFrame if you want three seconds.

function animate(){
    if (checking something){
        setTimeout(animate, 3000);
    } else {
        requestAnimationFrame(animate);
    }
}
  • Related