javascript setInterval 和 clearInterval,如何只运行 1 次?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13686867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:28:31  来源:igfitidea点击:

setInterval and clearInterval, How to run only 1 time?

javascriptjqueryfunction

提问by Vural

I only want to run the function 1 time.

我只想运行该函数 1 次。

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?

我只想调用 setInterval 中的函数 1 次。我怎样才能用 setInterval 和 clearInterval 做到这一点?

Or is there another technique to do it?

或者有其他技术可以做到吗?

回答by dsgriffin

Use the setTimeoutmethod if you only want it to run once.

如果您只想运行一次,请使用setTimeout方法。

Example:

例子:

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

回答by Curt

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

如果您只想运行一次代码,我建议您setTimeout改用:

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


'setInterval' vs 'setTimeout'

“setInterval”与“setTimeout”

回答by Matteo Tassinari

Use setTimeoutinstead:

使用setTimeout来代替:

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

this will execute the function only once after timeoutmilliseconds.

这将在timeout毫秒后仅执行一次该函数。