Eric Mitjans
Eric Mitjans

Reputation: 2179

Reloading object and triggering function in interval with jQuery

I have a file.js looking like this:

var mycompliments = {
        interval: 2000,
        fadeInterval: 4000,
        morning: [
            'Good morning, handsome!',
            'Enjoy your day!',
            'How was your sleep?'
        ],
        afternoon: [
            'etc'
        ],
        evening: [
            'chaning'
        ]
}

This data is used by another function and displayed in the frontend.

How could I trigger a reload of this file and execute the function every X seconds to update the content on the frontend?

The file using this data looks like this:

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)
}

I've tried setting a setinterval, but it didn't work.

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

        var loaded = data;
        console.log(loaded);
        compliments.updateCompliment(loaded);

        setTimeout(functionToLoadFile, 5000);

});
}
setTimeout(functionToLoadFile, 5000);

UPDATE:

Now the console shows that the file is reloaded every 5 seconds, but it's not updated into the frontend. I think is not correctly passed into updateCompliment function?

UPDATE 2:

The console logs this:

var mycompliments = {
    interval: 2000,
    fadeInterval: 4000,
    morning: [
        'Good morning, handsome!',
        'Enjoy your day!',
        'How was your sleep?'
    ],
    afternoon: [
        'etc'
    ],
    evening: [
        'wowowow'
    ]
}

UPDATE 3

I've managed to update compliments every 5 seconds, but I can't seem to be able to trigger compliments.updateCompliment(); from inside the function!

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

        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


        };
        console.log(compliments);

        setTimeout(functionToLoadFile, 5000);

        compliments.reload = function () {

            compliments.updateCompliment(compliments);
        }
    });

}
setTimeout(functionToLoadFile, 5000);

Upvotes: 0

Views: 125

Answers (3)

Neil Atkinson
Neil Atkinson

Reputation: 774

Be sure to place your setInterval(functionToLoadFile, 5000); outside the actual function functionToLoadFile.

Re Update 2: You're not actually updating the compliments object with the compliments you fetch from 'js/mycompliments.js'. The newly fetched compliments are stored in the loaded variable, but you don't do anything with that data. You need to update the compliments object with the newly fetched data before running the compliments.updateCompliment() function.

Re update 3:

There are a number of problems with your code at present, so several reasons why it isn't working.

  • You have defined a reload function on the compliments object which when it is executed (aka called) will execute (aka call) the updateCompliment function. The reason updateCompliment isn't being called is that you don't ever call the reload function. (Incidentally defining a reload function here is serving no purpose; just call the updateCompliment function directly).
  • You still aren't using the data you're fetching. The jQuery.get('js/mycompliments.js', function(data) {...}) is pointless if you aren't going to do anything with the data.
  • I am still doubtful about whether your data returned from the server is actually what you think it is.
  • The compliments object when first initialised is subtly different from the object you say you're returning from the server. If you were actually using the data from the server this would likely cause be causing you problems.
  • You aren't currently using the spliceIndex variable, so if you intended it to be used then use it or just remove that code.
  • You don't need to slice() arrays all the time.

I don't think I can help you further. This problem may be beyond your current Javascript skill level. I'm not saying give up, but I think you have a lot more learn and I can't cover it all it a single answer to a stack overflow question.

Upvotes: 1

hewo
hewo

Reputation: 816

You could try something like this:

function load_script() {   
  $.getScript('js/mycompliments.js', function() {
    time = setTimeout(function() {
      load_script();
    }, 30 * 1000);
  }); 
}; 
load_script();

Upvotes: 0

Reda
Reda

Reputation: 1379

Instead of setInterval, try using setTimeout instead. Using setInterval for requests is generally a bad idea as the request could timeout and cause a bunch of other requests clogging up the queue. But be sure to also include setTimeout in the failure callback as well.

Upvotes: 1

Related Questions