SetInterval inside a hook?

Is there a way to set a regular interval to check inside a LiveView hook?
We need to check every cycle and then push a event to LiveView.
The ideia is to identify the document focus “user is back” and then update the liveview.
We have a basic javascript part to identify that, but can’t send events outside a hook.

basic hook interval

const documentFocus = {
  mounted() {
    setInterval(myFun, 500);
  },

  updated() {},

  destroyed() {},
};

It only triggers once.

Thanks! :smiley:

1 Like

This is our current working hook approach.

export function checkDocumentFocus(obj) {
  obj.pushEvent("userback", {});
}

function eventListener(obj) {
  window.addEventListener("focus", (event) => {
    checkDocumentFocus(obj);
  });
}

const documentFocus = {
  mounted() {
    eventListener(this);
  },

  updated() {},

  destroyed() {},
};

export default documentFocus;

I’m not sure to really get what you want to achieve.
Did you try the phx bindings yet?

https://hexdocs.pm/phoenix_live_view/bindings.html#focus-and-blur-events

And, even if this is not your issue yet: when registering a setInterval in a hook, don’t forget to stop it in the destroyed callback

1 Like