Brahim
July 1, 2023, 12:02am
1
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
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
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
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)
2 Likes