Category: How do I do X?
Updated

This solution is summarized from an archived support forum post. This information may have changed. If you notice an error, please let us know in Discord.

How do I use setInterval to call a JS Object?

Issue

I am trying to display and refresh a moment.js object every second in a text widget using setInterval, but it doesn't seem to work even though my code is correct. The function, which is async, runs fine statically, but not with setInterval. I tried adding it to the onChange event of a Switch widget, but it still doesn't work. Can anyone help me figure out what I'm missing?

Resolution

The issue was that the code was binding the data from the function instead of running the function at set intervals. To solve this, the setInterval function should be triggered by the onChange event of a Switch widget. The text widget should only contain the binding - {{timesheet_process.myFun2.data}}.

Here is an example code snippet for the Switch widget onChange event:

{{(()=>{
const id = 'autoupdate';
if(Switch1.isSwitchedOn) {
setInterval(() =>
timesheet_process.myFun2(), 2000, id);
} else {
clearInterval(id);
}
})()}}

Additionally, it was mentioned that the myFun2 function returns a moment.js object. In this case, the code in the text widget should be updated to properly bind to this data:

{{timesheet_process.myFun2().format("HH:mm:ss")}}

Overall, the solution involves properly triggering the setInterval function and using the correct binding syntax in the text widget to display the moment.js object.