there is a variable that is passed to the function

var relsi; 

and if the variable is 1 , then the function performs one action, if the variable is 2 , then the other actions. and the problem is that after performing some actions, it redirects to another function, which changes the value of relsi and starts the timer to perform other setTimeout actions, but in the end the timer does not work and this action is executed immediately.

  function mybackpack() { save = []; var name = []; var item_id = []; backpack = []; var url = 'google.com'; request(url, function(err, res, body){ if(err){console.log(err);} else{ неважно что тут }); if(Relsi === 1) { fs.writeFileSync('./app/data.json', JSON.stringify(backpack, null, 4)); StartSell() } if(Relsi === 2) { CreateOrders() } }; }); } 

    1 answer 1

    Option 1 (telepathic).

    Because you put parentheses after the function name, trying to link to it in setTimeout .

    Option 2 (solution in the forehead).

    Because in your code, by the time the condition is checked in the second if , the function called in the first if has already changed the value of the variable.

     if(Relsi === 1) { ... } else if (Relsi === 2) { ... } 

    or

     var localRelsi = Relsi; if(localRelsi === 1) { ... } if (localRelsi === 2) { ... } 
    • setTimeout (function () {mybackpack ();}, 1000 * 60 * 45) is not correct? - Redbeard
    • what's this? what for? - Igor
    • look at me there is such function function some () {relsi = 2; setTimeout (function () {mybackpack ();}, 1000 * 60 * 45); } but the function is executed immediately, does not wait 45 minutes, take into account the fact that I already called this function (mybackpack ()) with the value relsi = 1; - Redbeard
    • Put the else before the second if . - Igor
    • Thanks kind of helped, and why does this work so? I do not understand the logic; in theory, and so it should have been normally executed - Redbeard