javascript - 使用 setInterval 调用对象内部的方法不起作用

标签 javascript jquery

我正在尝试使用 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/

相关文章:

javascript - Node.js:多维数组赋值

javascript - 为什么我不能访问 jquery 函数中的变量

php - 如何在javascript中使用json数组

javascript - 我可以使用 jQuery 重新加载 div 吗?

javascript - Bootstrap 可折叠菜单在隐藏打开的 div 时打开

javascript - Jsf 命令按钮调用 javascript 函数然后刷新整个页面

javascript - 如何使用 JavaScript 定期检索页面输出并显示给用户?

javascript - AngularJs 服务,无法在本地存储

javascript - 使用 Div 获取类的特定实例

jquery - 选择2 : set hidden field value