我怎样才能重新调用这个函数?没有经验的ES6

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

我不知道如何在页面加载后运行第二次调用counter()

我想,我做了一个新的计数器“实例”。这确实有效但必须有正确的方法。我需要在重播()中调用它

/**
 * @fileoverview demo 
 */

class ReVideo {
    constructor() {
        this.time = 5;
...
        this.timer = document.getElementById("update");
        this.counter = setInterval(() => this.countdown(), 1000);
        this.fader = fader();
        this.counter2 = "";
...

        this.retry.addEventListener('click', () => this.replay());
...
    }

    countdown() {
        this.time--;
        if (this.time > -1) {
            this.timer.innerHTML = "seconds remaining: " + this.time;
        } else {
            this.timer.innerHTML = "You Lose!";
            this.watch.style.display = "block";
            this.retry.style.display = "block";
            clearInterval(this.counter);
            clearInterval(this.counter2);
            this.coins++;
            this.coinCount.innerHTML = "Coins: " + this.coins;
        }
        this.notice.style.visibility = "visible";
        this.notice.innerHTML = "Loaded";
    }

...

    replay() {
        this.time = 5;
        this.watch.style.display = "none";
        this.notice.style.visibility = "hidden";
        fader("Loaded");
        this.retry.style.display = "none";
        this.counter2 = setInterval(() => this.countdown(), 1000);
        this.counter2;
    }
...

}
new ReVideo();

如果我说counter();它不会运行;

javascript ecmascript-6
1个回答
0
投票

你可以有一个帮手counter函数返回intervalID像:

counter () {
  const interval = setInterval(() => this.countdown(), 1000);
  return interval;
}

在你的构造函数中,你可以将intervalID分配给一些变量,如:

this.interval = counter();

然后你可以通过传递像intervalID这样持有clearInterval(this.interval);的变量来停止计数器

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