clearInterval when msg.payload changes


I’ve been building an AngularJS component that creates a table of items that are passed to it through msg.payload and are clickable using the scope.$watch and pass a value out through msg.payload. One part is a countdown clock related to the item in each row.

The component generally works, but if I cause a change in the data, the setInterval creates a second interval without clearing the first, and I end up with 2 countdown clocks on the same row, one on top of the other.

Obviously I need a clearInterval, but what’s happening is that the $scope.$watch is waiting for a msg.payload, and it calls this countdown clock function. It seems like the logical place to put the clearInterval is in the $scope.$watch after it has figured out it has new data. The $scope.$watch function calls the countdown clock function.

Any thoughts on when/how I can call this clearInterval.

Using an HTML form in a Dashboard Template node

You may get some ideas from what I did


Answered my own question. I needed to move the setInterval function from the countdown function into the $scope.$watch. Then I needed to clearInterval before I set it. In this way, when new data comes in to drive the countdown, it will clear out the old interval.

Final code.

(async function($scope) {
    let setIntervalId = 0 // first time
    $scope.$watch('msg.payload', async function(payload,oldpayload) {
        clearInterval(setIntervalId) // new data clear
        if (payload != oldpayload) {
            setIntervalId = setInterval( function(){
        await new Promise((resolve, reject) => setTimeout(resolve, 3000))
    await new Promise((resolve, reject) => setTimeout(resolve, 3000))