Thursday, 27 April 2017

Running a random select and timer function together in javascript

I'm currently working on a twitter bot with javascript, node and the twit package. I have set up a timer and a random select function, so my aim is that the bot tweets every 60sec and chooses a random sentence from my array. When I test both bits alone (the timer OR the random function) they work but for some reason I can't make them work in conjunction. I tried to declare a variable for the getRandomSentence() function (like var tweet = getRandomSentence(tweet)) but then I would get this error return sentences[index]; ^

TypeError: Cannot read property 'NaN' of undefined

The code like I've uploaded it now runs but the timer doesn't seem to work.

// timer
setInterval(getRandomSentence, 1000*60)

// random
  var sentences = [

  'sentence1',

  'sentence2',

  'sentence3.',

  'sentence4',

  'sentence5',

  'sentence6'

    ],
    maxSentences = sentences.length;

    function getRandomSentence() {
        var index = Math.floor(Math.random() * (maxSentences - 1));
        return sentences[index];
    }

//  tweets
//
T.post('statuses/update', { status: getRandomSentence()}, tweeted);

function tweeted (err, data, response) {
if (err) {
 console.log(err);
}
else {
 console.log("It works.");
 }
}

I would really appreciate if someone could help me here! I'm still an absolute newbie.



via Marie Ella

No comments:

Post a Comment