Home > Net >  Delay calling a function by a few seconds?
Delay calling a function by a few seconds?

Time:12-15

I am have a problem with setTimeout and setInterval functions. Here is my code:

if (a == true)
{
  setTimeout(myFunction, 2000);
}

It does delay calling the function by 2 seconds however it calls it multiple times while I want to call it just once if the condition are met and with a delay of 2 seconds I have used setInterval but I had similar problems with that

CodePudding user response:

It sounds like the condition is met multiple times, and you only want the first true evaluation of the condition to trigger the delayed function call. In that case, you just need to track whether or not it's already been run, and update it to true afterward:

// In a shared scope so it can be modified inside the delayed function
var didRunWithDelay = false;

// Elsewhere
if (conditionWasMet && !didRunWithDelay) {
    didRunWithDelay = true;
    setTimeout(delayedFunction, 2000);
}

// Your function
function delayedFunction() {
    // Do stuff
}

If your condition can be true multiple times, the delayed function will be called each time. So you track, in a boolean, whether or not that condition has triggered the setTimeout already. If not, you call it, otherwise skip it.

CodePudding user response:

The function setTimeout() takes as parameter a function followed by a number that corresponds to the time in milliseconds after which the function will be executed.

It is also important to keep in mind that the setTimeout() function executes asynchronously, i.e. the functions called afterwards will be called directly and not after the time passed in parameter has elapsed.

setTimeout(() => {console.log("this is the first message")}, 5000);
setTimeout(() => {console.log("this is the second message")}, 3000);

In this example, the second message will be displayed 2 seconds (2000ms) before the first!

It is possible to pass as parameter either reference to a function via its name and parameters or to use an annonymous function via writing () => { code here }.

Have a nice day!

  • Related