yanisla35
yanisla35

Reputation: 153

Execute function only once - Depending conditions

I know how to execute a function once, this is not the question

First, this is my code

 var executed1 = false;
 var executed2 = false;
 var executed3 = false;

function myFunction()
{   
    if(-------------------)
    {
        //Verification - If the others conditions have ever been called
        if (executed2)
        {
            executed2 = false;
        }
        else if(executed3)
        {
            executed3 = false;
        }


        //Verification - If the condition have ever been called during this condition = true;
        if (!execution1) 
        {
            execution1 = true;
            //My code here ...
        }        
    }
    else if (-------------------)
    {

        if (executed1)
        {
            executed1 = false;
        }
        else if(executed3)
        {
            executed3 = false;
        }

        if (!execution2) 
        {
            execution2 = true;
            //My code here ...
        }                            
    }
    else if (-------------------)
    {
        //Same thing with execution3         
    }
}
setInterval("myFunction()", 10000);

I'll take the first condition, for example

(1) If the condition is true, I want to execute my code but only the first time : as you can see, my function is executed every 10s. As long as the first condition is true, nothing should append more.

If the first condition becomes false and the second condition true, it’s the same process.

But now, If the first condition ever been true and false, I would like that if the condition becomes true again, it will be the same thing that (1)

Is there any way to read a cleaner code to do that ? Because, now there are only 3 conditions, but there may be 100.

Upvotes: 1

Views: 625

Answers (1)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92337

use clearInterval to stop execution your function and one if to check conditions

var fid = setInterval(myFunction, 1000);
var cond = [false,false,false];

function myFunction()
{   
  console.log(cond.join());
  
  // check conditions in some way here (e.g. every is true)
  if(cond.every(x=>x)) { 
    clearInterval(fid);
    console.log('Execute your code and stop');
  } 
  
  // change conditions (example)
  cond[2]=cond[1];
  cond[1]=cond[0];
  cond[0]=true; 

}

Upvotes: 1

Related Questions