更新 javascript 中的延迟函数

update a delayed function in javascript

我有一个简单的 javascript 函数可以加载文档就绪:

var start = 1;
var speed = 1000;
    $(document).ready(function () {
        go();
        setInterval(function () {
            go();
        }, speed);

详细功能如下:

function go() {
    $("#score").html(start.toLocaleString());
    start += 1;
}

这基本上是一个从数字 1 开始到无穷大的计数器,速度为 1000 毫秒。事情是这样的,现在:我有另一个功能:

function modify() {
  speed = 500;
}

调节主函数的setIntval速度。问题是它仅适用于页面刷新。如何在不刷新页面的情况下实时更新?

您无法更新当前的,您必须停止它并设置一个新的计时器,它的功能相同但延迟不同。

var speed = 1000;
var start = 1;
function go() {
    $("#score").html(start.toLocaleString());
    start += 1;
}

function startGoTimer(){
  return = setInterval(function () {
      go();
    }, speed);
}

function modifyTimer( previousTimer, newDelay=500) {
    clearInterval(previousTimer);
    speed = newDelay;
    startGoTimer();
}

var timer = startGoTimer();
// Some code
modifyTimer(timer, 500);

为了好玩,我刚刚测试了如果你只是改变时间会发生什么:

var timing = 1000;
var interval = setInterval(function(){console.log("test")}, timing);
// Now we get a log every 1000ms, change the var after some time (via console):
timing = 10;
// still an interval of 1000ms.

一个非常简单的解决方案是利用 setInterval 参数 ,

var intervalID = scope.setInterval(func, delay[, param1, param2, ...]);

并将 speed 作为 param1 传递。

然后,在每个时间间隔,检查它是否发生变化,如果发生变化,则清除现有计时器并启动一个新计时器。

堆栈片段

var start = 1;
var speed = 1000;
var timer;

$(document).ready(function() {
  go();
  timer = setInterval(function(p) {
    go(p);
  }, speed, speed);
  
  // for this demo
  $("button").click(function(){ speed = speed/2});
})

function go(p) {
  if(p && p != speed) {
    clearInterval(timer);
    timer = setInterval(function(p) {
      go(p);
    }, speed, speed);
  }
  
  $("#score").html(start.toLocaleString());
  start += 1;
}
div {
   display: inline-block;
   width: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="score">0</div>

<button>Modify</button>