每隔X秒加载js文件并更新内容

时间:2016-01-28 16:19:01

标签: javascript jquery ajax

我有一段JS代码在前端显示和数据数组。看起来像这样:

var compliments = {
    complimentLocation: '.compliment',
    currentCompliment: '',
    complimentList: {
        'morning': mycompliments.morning,
        'afternoon': mycompliments.afternoon,
        'evening': mycompliments.evening
    },
    updateInterval: mycompliments.interval || 30000,
    fadeInterval: mycompliments.fadeInterval || 4000,
    intervalId: null
};

compliments.updateCompliment = function () {

    var _list = [];

    var hour = moment().hour();

    if (hour >= 3 && hour < 12) {
        _list = compliments.complimentList['morning'].slice();
    } else if (hour >= 12 && hour < 17) {
        _list = compliments.complimentList['afternoon'].slice();
    } else if (hour >= 17 || hour < 3) {
        _list = compliments.complimentList['evening'].slice();
    } else {
        Object.keys(compliments.complimentList).forEach(function (_curr) {
            _list = _list.concat(compliments.complimentList[_curr]).slice();
        });
    }

    var _spliceIndex = _list.indexOf(compliments.currentCompliment);
    if (_spliceIndex !== -1) {
        _list.splice(_spliceIndex, 1);
    }

    var _randomIndex = Math.floor(Math.random() * _list.length);
    compliments.currentCompliment = _list[_randomIndex];

    $('.compliment').updateWithText(compliments.currentCompliment, compliments.fadeInterval);

}

compliments.init = function () {

    this.updateCompliment();

    this.intervalId = setInterval(function () {
        this.updateCompliment();
    }.bind(this), this.updateInterval)

}

在页面加载时触发最后一个函数,从外部js文件中抓取var compliments的内容

我尝试做的是包含超时,以便每隔X秒重新加载外部文件,并替换前端显示的内容。

我已尝试在文件末尾添加此超时功能(因此它会在页面加载时触发,之后会超时)但到目前为止还没有运气:

function functionToLoadFile(){
  jQuery.get('js/mycompliments.js', function(data) {

      compliments.init = function () {

        this.updateCompliment();

        this.intervalId = setInterval(function () {
            this.updateCompliment();
        }.bind(this), this.updateInterval)

      }

   setTimeout(functionToLoadFile, 1000);
});
}

我错过了什么?

0 个答案:

没有答案