Pause three.js simulation when switching tabs?

That does not explain how I can simply pause tab while not in use with the above code?

That does not explain how I can simply pause tab while not in use with the above code?

if ( delta < 500 ) spriteMixer.update(delta);

requestAnimationFrame is not called while the browser window isn’t in focus. So when the user navigates away for say, 5 seconds, then switches back, you will have delta = 5000 and spriteMixer.update will not be called.

4 Likes

It didn’t work. Look at between ‘line{s} 46 and 177’. It doesn’t stop messing up when switching tabs. It seems to be showing both sprite animations at same time when I flip to another tab wait some seconds then go back to current tab, it shows multiple animation sequences when outside of the tab switching to multiple other animation sequence{s}.

Heres demo :

http://babylontesting.epizy.com/Three.js/three-SpriteMixer/

Heres source code :

http://babylontesting.epizy.com/Three.js/three-SpriteMixer/js/mainframes/game-mainframe.js

The pageVisibility API worked on listening to the tab changes! Thanx @Mugen87 for that.

Here is how I’d call these methods from outside of the Loop class:

document.addEventListener('visibilitychange', e => this.handleVisibilityChange(e));

handleVisibilityChange(e) {
	if (document.visibilityState === 'hidden') {
		this.loop.stop();
	} else {
		this.loop.start();
	}
}

Still, inside the Loop class I was also having trouble trying to stop the loop: Using renderer.setAnimationLoop(null) just wouldn’t work…

What worked for me was stoping the clock on stop(), resuming it on start()

export class Loop {
    updatables = []

// ...

start() {
	this.clock.start();  // <-- here

	this.renderer.setAnimationLoop(() => {
		this.tick();

		this.renderer.render(this.scene, this.camera); // render a frame
	});
}

stop() {
	this.clock.stop();  // <--here
}

tick() {
	const delta = this.clock.getDelta();

        // ...

	for (const object of this.updatables) {
		object.tick(delta);
	}
}

This way the objects’ tick() function won’t be called, and we can switch tabs without having objects in crazy positions when we’re back.

Hope it helps

1 Like

doesnt clock need to be set to clock.autostart = false? if say we dont want it starting by itself when stopped purposely