Node.js中带有回调函数的setInterval、setTimeout

setInterval, setTimeout with callback function in Node.js

本文关键字:setInterval setTimeout 函数 回调 js Node      更新时间:2023-09-26

我在Node.js中编写了一个应用程序,它将像模拟游戏fg.football match一样成为引擎。我想有"在线广播",为此我创建了如下功能。我想知道为什么我的代码不能正常工作。我所期待的:

等待

等待

等待

等待

等待

等待

等待

等待

等待

等待

等待

等等。

但我不知道我的代码出了什么问题,看看这个:

getText: function() {
    console.log("something");
},
setDelay: function(callback) {
    var that = this;
    setTimeout(function() {
        callback();
    },5000);
},
play: function() {
    var that = this;
    setInterval(function(){
        console.log("wait");
        that.setDelay(that.getText);    
    },1000);
},

我得到了这样的东西:

等待

等待

等待

等待

等待

等待

等待

等等。

任何想法都将不胜感激。

这是因为您每秒调用setDelay()

getText: function() {
    console.log("something");
},
setDelay: function(callback) {
    var that = this;
    setTimeout(function () {
        callback();
    }, 5000);
},
play: function() {
    var that = this;
    setInterval(function () {
        console.log("wait");
        that.setDelay(that.getText); // << here
    }, 1000);
},

发生了什么:

1s->setDelay()->创建timeout1
2s->setDelay()->timeout2被创建
3s->setDelay()->timeout3被创建
4s->setDelay()->timeout4被创建
5s->setDelay()->timeout5被创建
6s->setDelay()->timeout6已创建//timeout1的5s已完成,因此它将启动
7s->setDelay()->timeout7已创建//timeout2的5s已完成,因此它将启动
8s->setDelay()->timeout8被创建//timeout3的5s完成,因此它触发
等等…

play函数内部,每秒钟都要运行that.setDelay,然后等待5秒钟才能运行console.log("something");

相反,您可以让两个setInterval运行:

play: function() {
    var that = this;
    setInterval(function () {
        console.log("wait");
    }, 1000);
    setInterval(function () {
        that.getText();
    }, 5000);
},

这样,每秒钟你就会得到一个"等待"的输出,每五秒钟你就会收到一个"某物"的输出。

圣诞快乐!

我会尝试取消两个混合的超时/间隔,并在达到循环限制后只清除/重置一个。这让它更容易理解。类似这样的东西:

function play(count) {
  var count = count || 1;
  var t;
  console.log(count);
  if (count !== 0 && count % 5 === 0) {
    clearTimeout(t);
    console.log('something');
    t = setTimeout(play, 5000, 1);
  } else {
    t = setTimeout(play, 1000, ++count);
  }
}
play();

演示

或者,根据您自己的代码:

var obj = {
  delay: 5000,
  timer: 1000,
  getText: function () {
    console.log('something');
  },
  play: function(count) {
    var count = count || 1;
    var t;
    if (count !== 0 && count % 5 === 0) {
      clearTimeout(t);
      this.getText();
      t = setTimeout(this.play.bind(this), this.delay, 1);
    } else {
      t = setTimeout(this.play.bind(this), this.timer, ++count);
    }
  }
}
obj.play();

演示