如何重置计时器并以角度2引发事件

时间:2018-03-06 15:27:04

标签: angular typescript timer rxjs

亲爱的stackoverflow主谋,

我是Angular 2的新手,目前正在开发我的第一个应用程序。总之,我想用计时器在屏幕上显示一个句子。当这个计时器达到0时,我希望它重置并显示下一个句子。我设法用一个可用于if语句的变量创建一个计时器,这会导致下一句话,但计时器不会再次开始倒计时。

这是我的代码:

constructor() {
let timer = Observable.interval(1000).take(11);
timer.subscribe(t=>this.tickerFunc(t));

}
tickerFunc(tick){
    this.ticks = tick;
    this.count = 10-this.ticks;
      if (this.count == 0){
        this.NextSen(this.x,this.y);
        this.count = 10;

我在这里从另一篇文章中提取原始计时器代码。 NextSen是一个已经正常工作的功能。所以我认为我没有用的表现。

我尝试将构造函数代码放在最后一句之下,这确实有效,但tickerFunc一直被调用,因此计时器不会停止。该代码看起来像这样

tickerFunc(tick){
  this.ticks = tick;
  this.count = 10-this.ticks;
  for (this.i = 0; this.i < this.sentences.length; this.i++){
    if (this.count == 0){
      this.NextSen(this.x,this.y);
      this.count = 10;
      let timer = Observable.interval(1000).take(11);
      timer.subscribe(t=>this.tickerFunc(t));
    }
  }

我也尝试了不同的计时器,但是这些不会输出我可以用来引发事件的变量。如果需要,我也可以提供这些。我知道简单地将this.count重新设置为10并不会导致时间,但我真的很想听听它是什么:)

我希望我的解释很明确,如果还有其他我需要说明的话请告诉我。提前谢谢。

3 个答案:

答案 0 :(得分:0)

以下代码段将在每10秒后在控制台“Time reset”中写入。您可以根据需要配置时间。希望这会对你有所帮助

ngOnInit(){

  var timeoutID;
  startTimer();     

  function startTimer() {
    timeoutID = window.setTimeout(resetTimer, 10000);        
  } 

  function resetTimer() {
    console.log('Time reset');
    window.clearTimeout(timeoutID);       
    startTimer();       
  }

}

答案 1 :(得分:0)

我设法使用此代码解决了问题:

this.countDown = Observable
  .timer(0, 1000)
  .map(tick => {
      if (10 - (tick % 11) == 0) {
        this.nextSentence();
      }
      return 10 - (tick % 11);
    }
  );

感谢您的评论!

答案 2 :(得分:0)

我在尝试进行其他类型的计时器重置时遇到了这个问题。我认为Rak2018有一个正确的主意,可以解释得更好一些。我更喜欢这种方式,因为它可以在javascript中使用,我认为它更具可读性,而且逻辑上也容易得多。

var sentinces = [
  "I'm a little teapot",
  "Short and stout",
  "Here is my handle",
  "Here is my spout",
  "When I get all steamed up",
  "Hear me shout",
  "Tip me over and pour me out!"
];

var timer; //: NodeJS.Timer;

function next(index) {
  clearTimeout(timer);
  if (!index) {
    index = 0;
  }
  document.getElementById("content").innerHTML = sentinces[index]
  if (index + 1 < sentinces.length) {
    timer = setTimeout(() => next(index + 1), 1000);
  }
}
<div id="content">Press Start</div>
<button onClick="next()">Start</button>

相关问题