1

Im trying to write two functions to work together, but when I pass through a variable from the first function to the second function, it comes out as undefined. Here are the functions:

function StartAlerter(){
    var rawdata = fs.readFileSync('./events/' + tevent)
    var cJSON = JSON.parse(rawdata)
    var notifier = cJSON.notifier
    var tdate = cJSON.epochtime
    var messagefile = JSON.parse(fs.readFileSync('./notifier/' + notifier, function(err){
        if(err) console.log('Issue with loading message file, setting to null'.red)
        console.log('Message file failed to load: ' + './notifier' + notifier)
    }));
    var messagecontent = messagefile.text.toString()
    waitforsend(tdate, messagecontent)
}

Second Function:

function waitforsend(tdate, messagecontent) { //https://stackoverflow.com/questions/22125865/wait-until-flag-true
    cdate = Math.floor(new Date().getTime())/1000 - 18000
    console.log(tdate)
    if(cdate <= tdate) {
       setTimeout(waitforsend(), 100);
    } else {
        console.log(messagecontent)
        client.channels.cache.get(eventchannelid.toString()).send(messagecontent)
    }
}

They have the proper values in StartAlerter(), but become undefined in waitforsend(). Why is this?

gjoe
  • 99
  • 1
  • 1
  • 7
  • Because of this: `setTimeout(waitforsend(), 100)`? You invoke the function on load, not after 100ms, and you don't pass `tdate` and `messagecontent`. – Zsolt Meszaros May 06 '21 at 19:56
  • 1
    `setTimeout(waitforsend(), 100);` will 1. call `waitforsend()` *immediately*, instead of after a delay. See [Why is the method executed immediately when I use setTimeout?](https://stackoverflow.com/q/7137401) 2. not pass any arguments to `waitforsend` See: [How can I pass a parameter to a setTimeout() callback?](https://stackoverflow.com/q/1190642) – VLAZ May 06 '21 at 19:56

0 Answers0