10

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?

dsgriffin
  • 66,495
  • 17
  • 137
  • 137
Vural
  • 8,666
  • 11
  • 40
  • 57

3 Answers3

28

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

Example:

 setTimeout(function() {
      // Do something after 5 seconds
 }, 5000);
dsgriffin
  • 66,495
  • 17
  • 137
  • 137
4

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

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

'setInterval' vs 'setTimeout'

Community
  • 1
  • 1
Curtis
  • 101,612
  • 66
  • 270
  • 352
4

Use setTimeout instead:

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

this will execute the function only once after timeout milliseconds.

Matteo Tassinari
  • 18,121
  • 8
  • 60
  • 81