在if语句中调用时,clearTimeout不起作用

时间:2017-02-13 20:53:41

标签: javascript cleartimeout

此代码应在结束前运行10秒,但如果您在10秒完成之前再次运行该功能,则应清除Timeout并再次启动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);
    };
  };




3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

在您的函数start中,timeUp始终设置为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秒过去,它就会清除间隔。

答案 2 :(得分: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>