How do you clear an interval inside a callback function?

Here is an example from my code run at Add function

const handlePlayFoam = (e) => {
      // Show foam effect by set opacity = 1
      ecs.Material.set(world, schemaAttribute.cursor(eid).foamEffectGo,
        {textureSrc: array[dataAttribute.cursor(eid).frame], opacity: 1})

      const intervalId = world.time.setInterval(() => {
        if (!dataAttribute.cursor(eid).isStop) {
          if (dataAttribute.cursor(eid).frame % 2 === 0 && Math.random() >= 0.43) {
            ecs.Material.set(world, schemaAttribute.cursor(eid).foamEffectGo,
              {textureSrc: array[dataAttribute.cursor(eid).frame], opacity: 0})
          } else {
            ecs.Material.set(world, schemaAttribute.cursor(eid).foamEffectGo,
              {textureSrc: array[dataAttribute.cursor(eid).frame], opacity: 0.9})
            dataAttribute.cursor(eid).frame++
          }

          if (dataAttribute.cursor(eid).frame > array.length - 1) {
            dataAttribute.cursor(eid).frame = 0
          }
        }
      }, 14)
    }

    world.events.addListener(world.events.globalId, 'RemoveCountDown', handlePlayFoam)

When the handlePlayFoam callback function runs, a loop will start inside this callback. It is assigned to intervalId. However, I cannot use world.time.clearInterval(intervalId) to clear it. How can I stop it completely?

Where in your code are you trying to call clearInverval?

Perhaps you want to declare intervalId outside of the callback:

let intervalId

const handlePlayFoam = () => {
  intervalId = world.time.setInterval(...)
}

handlePlayFoam()
world.time.clearInterval(intervalId)
2 Likes

Thanks for your support!

I have the same problem. I tried your code, but it reported the error

> TypeError: world.time.clearInterval is not a function

I think it should run in the local context of that entity. Therefore, I tried removing β€œworld.time.” and it ran smoothly :star_struck:. Here is my code:

let intervalId;
const handlePlayFoam = () => {
  intervalId = setInterval(...);
}

const removeThis = () => {
  clearInterval(intervalId); 
  world.deleteEntity(eid);
}

world.events.addListener(world.events.globalId, 'RemoveCountDown', handlePlayFoam);
world.events.addListener(world.events.globalId, 'GameOverEvent', removeThis);

Thanks for your support. But I have a question about how to remove an interval when it’s running global with add β€œworld.time.” before it.
For example:

intervalId = world.time.setInterval(...)

How do I remove it?

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.