javascript - 我的 setInterval 没有改变,即使我的变量是

标签 javascript html css setinterval

<分区>

这是我的 setInterval 代码片段:

  var t = 0;
  var speed = 1000;

// To display the speed
  setInterval(displaySpeed, 100);

  setInterval(timer, speed);

// To diplay the speed as well
function displaySpeed(){
  document.getElementById("Tem").textContent = speed;
}

function speedUp(){
  speed = speed - 100;
}

function slowDown(){
  speed = speed + 100;
 }

function timer(){
  t = Math.floor(Math.random() * 16) + 1;
  changeBackground();
}

speedUp() 和 slowDown() 连接到带有 onclick 的按钮。按钮将更改变量,但不会更改实际速度。定时器功能是在1到16之间选择一个随机数。

最佳答案

编辑:此代码显示了/u/torazaburo 在您的问题中的回答。 添加一个糖函数来重新创建间隔,speedUp()slowDown() 方法都需要清除它才能改变速度。

var intervalRef = setInterval(timer, speed);

function updateTimerSpeed(newSpeed) {
    intervalRef = setInterval(timer, newSpeed); 
}

function speedUp() {
  clearInterval(intervalRef);
  speed = speed - 100;
  updateTimerSpeed(speed);
}

function slowDown() {
  clearInterval(intervalRef);
  speed = speed + 100;
  updateTimerSpeed(speed);
}

关于javascript - 我的 setInterval 没有改变,即使我的变量是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45767876/

上一篇:jquery - css3是否允许数学计算

下一篇:html - 文本移动到不同的 div : css

相关文章:

javascript - 关闭浏览器时执行一些功能

javascript - $apply 未知提供者错误

javascript - 停止 AngularJS promise 链

javascript - Twilio 'RecordingUrl' 未传递到我的 Parse Cloud 代码

javascript - 如何在加载另一段动态 HTML 后附加动态 HTML?

javascript - 选择器面板,Javascript

HTML/CSS 对齐 div 中的多个元素

html - 隐藏文本直到 HTML 元素展开以显示它?

html - 在电子邮件模板中,邮件自动删除指针事件 : none in class

html - Css .gif 闪烁故障排除?