Menu Item - JavaScript error when it runs the 2nd time

I'm using this JavaScript code:

const daysRem = Math.ceil((new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1) - new Date()) / (1000 * 60 * 60 * 24));
returnToBTT(daysRem);

to get the # of days remaining in the current month and display it in my menubar.

When the Automation runs when I start BTT, it shows the correct value :white_check_mark:
But when it runs for a second time, I get this Syntax error message:

But when I "Run Script" it in BTT, it outputs the correct value no problem!

in BTT, best always wrap javascript code in a self executing function to avoid global variable collisions

(async () {

yourScriptHere

})()

Thanks @Andreas_Hegenberg

The simple script I mentioned before didn't work by adding Async... like this:

(async () {

const daysRem = Math.ceil((new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1) - new Date()) / (1000 * 60 * 60 * 24));
returnToBTT(daysRem);

})()

But this one worked :white_check_mark: :white_check_mark: :white_check_mark: :white_check_mark:

async function calculateDaysRemaining() {
  const daysRem = Math.ceil(
    (new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1) - new Date()) / (1000 * 60 * 60 * 24)
  );
  return daysRem;
}

async function main() {
  const daysRemaining = await calculateDaysRemaining();
  returnToBTT(daysRemaining);
}

main();

Damn sorry, I typed this on my smartphone yesterday and forgot a "=>"

It should be

(async () => {

const daysRem = Math.ceil((new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1) - new Date()) / (1000 * 60 * 60 * 24));
returnToBTT(daysRem);

})()
1 Like

It works!
So much better than what ChatGPT provided :slight_smile:

Thanks

Just for being complete (I'm in the process of collection useful tips for scripting to put into the docs), you can also put it in a named function and provide the name in BTT:

async function getRemainingDays() {
  const daysRem = Math.ceil((new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1) - new Date()) / (1000 * 60 * 60 * 24));
  return(daysRem);
}

(then normal return can be used and returnToBTT is not necessary)

1 Like

Thanks !