setTimeout - 单击后更改持续时间

问题描述 投票:0回答:1

我在 JS 中有 setTimeout 函数:

Interval = 20000;

timer = setTimeout(function loop(){ 
   //do something
   timer = setTimeout(loop, Interval);                  
}, 1);

$("#next_button").click(function(e) {                           
   Interval = 1;
}); 

为什么点击后缩短间隔不起作用

javascript settimeout
1个回答
0
投票

从技术上讲它是有效的,但代码没有做的是取消之前的

setTimeout
调用并启动一个新的调用,因此它会在某个时刻被调用

let intervalDuration = 2000

const loop = () => {
  console.log(`Interval Value:`, intervalDuration)

  timeoutId = setTimeout(loop, intervalDuration)
}

let timeoutId = setTimeout(loop, intervalDuration)

const button = document.querySelector('.button')

button.addEventListener('click', event => {
  intervalDuration = 500
  clearTimeout(timeoutId)

  loop()
})
<button class="button">Click Me</button>

© www.soinside.com 2019 - 2024. All rights reserved.