简体   繁体   中英

setTimeout not working properly with the twitter node.js api

I am trying to read from a file and tweet the contents sequentially ie a big file into 140 character chunks. i have verified that the other components of my code work correctly. at first, i was just using a for-loop but in that case, the order of the tweets got jumbled up and wasn't sequential. i thought it was because of load-balancing or something by the twitter servers, so i decided to use setTimeout to set a pause in the code. the code is demonstrated below:

var Twitter = require('twitter');

var client = new Twitter({
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
});

const fs = require('fs');

var long_string = fs.readFileSync(__dirname + "/tweetfromhere.txt").toString();


var short_string = new String("");

const tweet_length = 140;

if (long_string.length%tweet_length === 0)
{
   var num_tweets = long_string.length/tweet_length;
}
else
{
    var num_tweets = Math.floor(long_string.length/tweet_length);
    console.log(num_tweets);
}

for (i = 0; i <= num_tweets; i++)
{
    short_string = long_string.substr(i*tweet_length, tweet_length);
    var stat = {status: short_string}
    setTimeout(function(){
    client.post('statuses/update', stat,  function(error, tweet,response) {
  if(error) 
  {
    console.log(error);
  }
  //console.log(tweet);  // Tweet body. 
  console.log(response);  // Raw response object. 
  });

}, 3000);
}

I know something is wrong with the setTimeout portion because if I just try to console.log its output, it doesn't do it properly, instead just gives the same portion of the string to be tweeted n times.

Any pointers will be welcome. I am very new to Javascript, (this is like my first real Javascript code), so please go easy on me if I have made an obvious mistake. also i am using the twitter package installed by simply npm install twitter

var request = require("request");


var stats = [];
for (i = 0; i <= 4; i++)
{
   stats.push({status: "yolo "+i});
}

var interval = setInterval(function(){
   if(!stats || stats.length == 0)
   {
       console.log("end");
       clearInterval(interval);
   }
   else
   {
       console.log("post "+stats[0].status);
       stats.splice(0,1);
   }
}, 3000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM