2

此代码应在结束前运行 10 秒,但是如果您在 10 秒结束之前再次运行该函数,则应清除超时并重新开始 10 秒

  function start() {
    let counter = 0;
    let timeUp = true;
    let hello;
    setInterval(()=> {
      counter++
      console.log(counter)
    },1000);
    if (timeUp == false) {
      clearTimeout(hello)
      timeUp = true
      console.log('should run again with new clock')
      start()
    } else {
      console.log('new clock started')
      timeUp = false;
      hello = setTimeout(() => {
        timeUp = true
        console.log('end clock')
      }, 10000);
    };
  };

4

3 回答 3

2

当你start()再次调用时,这个新函数没有引用hellotimeUp 尝试这样:

let hello
let timeUp = true

function start() {
    let counter = 0;
    //let timeUp = true;
    //let hello;
    setInterval(()=> {
      counter++
      console.log(counter)
    },1000);
    if (timeUp == false) {
      clearTimeout(hello)
      timeUp = true
      console.log('should run again with new clock')
      start()
    } else {
      console.log('new clock started')
      timeUp = false;
      hello = setTimeout(() => {
        timeUp = true
        console.log('end clock')
      }, 10000);
    };
  };
  
  window.start = start

于 2017-02-13T21:05:28.870 回答
1

在您的函数内部starttimeUp始终设置为true,因此clearTimeout永远不会被调用。你做事的方式,你应该做timeUp一个全局变量,这样函数就可以“记忆”是否已经到达时间。

但是为什么需要设置两个间隔呢?您已经在跟踪已经过去的秒数,因此我们可以利用该时间间隔来确定 10 秒过去的时间。这大大简化了事情,并允许我们摆脱timeUp变量:

let interval;

function start() {
    let counter = 0;
    clearInterval(interval); // clear the previous interval
    interval = setInterval(() => { // set a new interval
        counter++;
        if (counter == 10) {
            console.log('end of clock');
            clearInterval(interval);
        }
        console.log(counter);
    }, 1000);
}

这正是您想要的。每当start被调用时,它都会取消前一个间隔并创建一个新间隔。一旦 10 秒过去了,它就会清除间隔。

于 2017-02-13T21:04:56.940 回答
0

你的方法有点误导。我认为更好的方法是拥有一个可以启动的 Timer 对象:

function Timer() {
    var self = {
        // Declare a function to start it for a certain duration
        start: function(duration){
            self.counter = 0;
            self.duration = duration;
            clearTimeout(self.timeout); // Reset previous timeout if there is one
            console.log("New counter starting.");
            self.count();
        },
        // A function to count 1 by 1
        count: function(){
            console.log(self.counter);
            self.counter++;
            if(self.counter > self.duration){
                console.log('Time is up.');
            } else {
                self.timeout = setTimeout(self.count, 1000); // not over yet
            }
        }
        // and other functions like stop, pause, etc if needed
    };
    return self;
}

// Declare your Timer
var myTimer = new Timer();

// Start it on click
document.getElementById('start-btn').addEventListener('click', function(){
    myTimer.start(10);
}, true);
<button id="start-btn">Start the timer</button>

于 2017-02-13T21:16:32.510 回答