Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Hi have made some changes to the code. This works to console log a random sentence to tweet every 60 seconds:

var sentences = [
    'sentence1',
    'sentence2',
    'sentence3',
    'sentence4',
    'sentence5',
    'sentence6'
];
var maxSentences = sentences.length;

var sentenceToTweet = '';

function getRandomSentence() {
    var index = Math.floor(Math.random() * (maxSentences - 1));

    sentenceToTweet = sentences[index];

    console.log(sentenceToTweet);

    setTimeout(getRandomSentence, 1000 * 60);
}

getRandomSentence();
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!