Is it possible to have a Needle project to continue to run when the tab is not in focus

Is it possible to have projects build with Needle update when the tab is not in focus, similar to checking the Run In Background for builds in Unity?

Original Post on Discord

by user 259070246382469121

Have you tried setting this.context.runInBackground from one of your scripts?

Hey @marcel :cactus: , yes I had already tried setting that but it didnt have any impact, so was wondering if there was something else I needed to do.

by user 259070246382469121

Ah sorry - yes we’re currently subscribed to the three renderloop which useses the browser animation frame - this is not called for inactive tabs.
You could theoretically add a little script that adds that tho by listening to the browsers visibility change event (when the tab becomes inactive) and then call this.context.update(timestamp:...) from that script using an interval (I think)

Thanks for the answer Marcel. I haven’t been able to get that to work the past 25 mins or so, but I will look in to it further. Good to know it wasn’t something obvious I was missing.

by user 259070246382469121

export class RunInInactiveTab extends Behaviour {

    awake(): void {
        window.addEventListener("visibilitychange", this.onVisibilityChanged)
    }

    private interval?: number;

    onVisibilityChanged = () => {
        const dt = .01;
        const interval = 1000 * dt;
        console.log(document.visibilityState, this.interval)
        if (document.visibilityState === "hidden") {
            // tab is inactive
            if (this.interval !== undefined) return;
            this.interval = setInterval(() => {
                if(document.visibilityState === "visible") {
                    clearInterval(this.interval);
                    this.interval = undefined;
                    return;
                }
                console.log("RUNNING IN BACKGROUND", document.visibilityState, Date.now())
                this.context.update(dt)
            }, interval);
        }
        else {
            // tab is active
            clearInterval(this.interval);
            this.interval = undefined;
        }
    }
}

try this (edited ^)

Thanks for your help Marcel.

by user 259070246382469121