javascript 如何每隔几秒执行一次操作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6909692/
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-25 22:18:08  来源:igfitidea点击:

How to perform an action every couple of seconds?

javascript

提问by Iladarsda

Can someone quickly and simply explain to me how to perform an action every couple of seconds using

有人可以快速简单地向我解释如何使用

var timeOut = setTimeout(FunctionName, 5000);

I want to run a function every 5 seconds.

我想每 5 秒运行一次函数。

回答by James Allardice

As you asked for a method using setTimeout:

当您要求使用setTimeout以下方法时:

function doStuff() {
   console.log("hello!");
   setTimeout(doStuff, 5000);
}
setTimeout(doStuff, 5000);

But it would probably be better to use setInterval:

但最好使用setInterval

function doStuff() {
   console.log("hello!");
}
setInterval(doStuff, 5000);

回答by miku

Just put setTimeoutat the end inside your function, with a call to itself - like a delayed tail-recursion.

只需将setTimeout其放在函数的末尾,并调用自身 - 就像延迟尾递归一样。

回答by vaidas

In the example below, when a button is clicked, the input field will start to count (for ever), starting at 0.

在下面的示例中,当单击按钮时,输入字段将开始计数(永远),从 0 开始。

<html>
  <head>
    <script type="text/javascript">
      var c = 0;
      var t;
      var timer_is_on = false;

      function timedCount() {
        document.getElementById('txt').value = c;
        c = c + 1;
        t = setTimeout(timedCount, 1000);
      }

      function doTimer() {
        if (!timer_is_on) {
          timer_is_on = true;
          timedCount();
        }
      }
    </script>
  </head>
  <body>
    <form>
      <input type="button" value="Start count!" onclick="doTimer()">
      <input type="text" id="txt" />
    </form>
  </body>
</html>

回答by Mark Redman

you can do something like:

您可以执行以下操作:

$(document).ready(function () 
        {
setTimeout(nextNotice, 5000);
}
function nextNotice()
{
// do stuff 
setTimeout(nextNotice, 5000);
}

回答by Igor Dymov

Use setInterval:

使用setInterval

var timeOut = setInterval(nextNotice, 5000);

回答by Rob Stevenson-Leggett

var myFunction = function() { 
     //Do stuff
     AnotherFunction();
};

var timeOut = setInterval(myFunction, 2000);