Node.js中带有回调函数的setInterval、setTimeout
setInterval, setTimeout with callback function in Node.js
我在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();
演示
- Firebase迁移-简单的Firebase.set没有'不再工作了——旧的还是新的
- Ember Data DS.Model's set函数不起作用
- node.js:setInterval()正在跳过调用
- setInterval和clearInterval javascript无法按需工作
- Don'我不明白为什么我的setInterval+jQuery;不起作用
- setInterval游戏循环的范围问题
- C#asp.net mvc Set CheckBoxFor已检查的具有Model Value的属性
- 为什么JavaScript可以'找不到给定的InnerHTML并返回Cannot set property
- JavaScript setInterval problems
- 如何在Javascript中延迟setInterval
- 无法在基于Cordova的应用程序中读取Set Cookie标头
- 如何执行相同的setInterval()
- SetInterval在javascript对象中表现怪异
- 从setInterval方法移动到带有sprite的requestAnimationFrame
- 如何在悬停时暂停setInterval
- 在不兼容的接收器上调用的方法Set.prototype.add未定义
- 可以't获取setInterval函数以使用javascript中的this.function_name调用另一
- 删除对象时终止setInterval
- 使用setInterval()函数进行图像闪烁
- set backgroundPosition and setInterval