如何使SettieMout的刷新频率变量



我想要一个我正在写的函数以自动自动调用自己。我希望能够通过第一次解析它自称的频率。然后,它将在内部使用JS settimeout((函数在同一频率上重复调用自身。

因此,您可以在下面的示例中看到我的内容:

function testFunction(refreshFrequ){
    setTimeout(function() {
        console.log("frequency: "+refreshFrequ);
        testFunction(refreshFrequ);
    }, refreshFrequ);
}
// run the 1st time
testFunction(5000);

问题在于,从第二次运行起来,这是无法评估的超时。控制台输出提供了这里发生的事情的线索:

频率:未定义

我将如何工作,到目前为止什么都没有帮助。

尝试窗口setInterval((方法。另请参阅此答案,此答案以获取更多信息。

var autoInterval;
var elapsed = 0;
function myStartFunction(refreshFrequ) {
  if (!autoInterval) {
    autoInterval = setInterval(function() {
      elapsed++;
      document.getElementById("txt").innerHTML = refreshFrequ * elapsed + " elapsed.";
      console.log("frequency interval: " + refreshFrequ + " x " + elapsed);
    }, refreshFrequ);
  }
}
function myStopFunction() {
  if (autoInterval) {
    clearInterval(autoInterval);
    autoInterval = null;
    elapsed = 0;
    document.getElementById("txt").innerHTML = "Interval was reset.";
    console.log("interval stopped");
  }
}
myStartFunction(5000);
<p>The setInterval() method has started automatically.</p>
<button onclick="myStartFunction(1000)" title="Start with 1000 ms interval. Clicking this button while the event is active should not create a new interval instance.">Start</button> <button onclick="myStopFunction()" title="Click to stop and clear the interval instance.">Stop</button>
<p id="txt">0 elapsed.</p>

edit :尽管没有提及潜在的重复函数调用,但应考虑其他答案,尤其是如果可以任意执行事件。为了防止重复的事件与原始实例堆叠在一起,提出了if语句。否则,每个额外执行的函数将导致一个唯一的实例,然后可以进一步创建不可阻挡的多个事件,因此我必须在应得的信用额的情况下给予信用。tymek!

您可能需要使用setInterval

var testFunction = (function () { // This will "build"/"enclose" our function
    var handle = null; // ID of the interval
    return function (freq) {
      if (handle !== null) clearInterval(handle);
      handle = setInterval(function() {
        console.log("frequency: " + freq);
      }, freq);
    };
})();

如果您重新定位间隔,则不会创建另一个实例(具有2个函数滴答(。

您可以了解有关setInterval的更多信息:https://www.w3schools.com/jsref/met_win_setinterval.asp.asp有关JavaScript函数如何工作的更多信息在https://developer.mozilla.org/en-us/docs/web/javascript/closures/closures

最新更新