我正在尝试使用 setInterval()
函数使用对象内部的方法轮询我的服务器。代码如下所示:
(function(){
var teacherZone = {
init: function(){
this.cacheDOM();
this.bindEvents();
this.pollServer(); // get the list of lessons
},
cacheDOM: function(){
this.$showLessons = $('#showLessons');
this.$lessonsTemplate = $('#lessonsTemplate');
},
bindEvents: function(){
},
pollServer: function(){
alert('Polled');
}
}
teacherZone.init();
setInterval(teacherZone.pollServer(), 1000)
})();
这会调用alert()两次,但之后就不再调用了。不知道我哪里出错了。
如何以设定的时间间隔重复调用对象内部的方法?
更新代码:
(function(){
var teacherZone = {
interval: 5000,
init: function(){
this.cacheDOM();
this.bindEvents();
setInterval(function(){
teacherZone.pollServer(); // get the list of lessons
}, teacherZone.interval);
},
cacheDOM: function(){
this.$showLessons = $('#showLessons');
this.$lessonsTemplate = $('#lessonsTemplate');
},
bindEvents: function(){
},
pollServer: function(){
alert('Polled');
// data = {
// name: 'John'
// };
// this.$showLessons.html(Mustache.render(this.$lessonsTemplate.html(), data));
}
}
teacherZone.init();
teacherZone.pollServer();
})();
最佳答案
您需要删除括号,因为您立即调用该函数并且不移交该函数。
setInterval(teacherZone.pollServer, 1000)
// ^^
关于javascript - 使用 setInterval 调用对象内部的方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42396445/