Vural
Vural

Reputation: 8748

setInterval and clearInterval, How to run only 1 time?

I only want to run the function 1 time.

timerA = setInterval(function()
         {
            //codes..
            clearInterval(timerA);
         }, 2000);

I want to call the function inside setInterval only 1 time. How can I do it with setInterval and clearInterval?

Or is there another technique to do it?

Upvotes: 11

Views: 22642

Answers (3)

Matteo Tassinari
Matteo Tassinari

Reputation: 18584

Use setTimeout instead:

setTimeout(function() { [...] }, timeout);

this will execute the function only once after timeout milliseconds.

Upvotes: 4

dsgriffin
dsgriffin

Reputation: 68606

Use the setTimeout method if you only want it to run once.

Example:

 setTimeout(function() {
      // Do something after 5 seconds
 }, 5000);

Upvotes: 33

Curtis
Curtis

Reputation: 103368

If you only want to run the code once, I would recommend using setTimeout instead:

setTimeout(function(){
   //code
}, 2000);

'setInterval' vs 'setTimeout'

Upvotes: 4

Related Questions