setInterval and clearInterval, How to run only 1 t

2020-07-13 10:29发布

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?

3条回答
Root(大扎)
2楼-- · 2020-07-13 11:04

Use setTimeout instead:

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

this will execute the function only once after timeout milliseconds.

查看更多
对你真心纯属浪费
3楼-- · 2020-07-13 11:20

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

Example:

 setTimeout(function() {
      // Do something after 5 seconds
 }, 5000);
查看更多
▲ chillily
4楼-- · 2020-07-13 11:26

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

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

'setInterval' vs 'setTimeout'

查看更多
登录 后发表回答