setTimeout not working after a peroid of time on device


#1

I am using the code below to auto log out a user when the token is due to expire. It works fine on the Android device for short periods of time (5 mins) but when I test for the hour needed it does not log out the user.
Also the buttons are unresponsive after coming back to the app.

Any ideas why this is not working?

private autoLogout(duration: number) {
    if (this.activeLogoutTimer) {
      clearTimeout(this.activeLogoutTimer);
    }
    this.activeLogoutTimer = setTimeout(() => {
      this.logout();
    }, duration);
  }

#2

You’re putting the app to the background right? Maybe it helps to add platform pause/resume listeners:

logoutAtTimestamp: number = null
activeLogoutTimer: NodeJS.Timer

constructor(
	private platform: Platform,
) {
	this.platform.pause
		.subscribe(() => {
			clearTimeout(this.activeLogoutTimer)
		})

	this.platform.resume
		.subscribe(() => {
			this.checkForLogout()
		})
}

private autoLogout(duration: number) {
	this.logoutAtTimestamp = Date.now() + duration
	this.startLogoutCheckTimeout()
}

startLogoutCheckTimeout() {
	this.activeLogoutTimer = setTimeout(() => {
		this.checkForLogout()
	}, 20000)
}

checkForLogout() {
	if (!this.logoutAtTimestamp) {
		return
	}

	if (this.logoutAtTimestamp > Date.now()) {
		this.startLogoutCheckTimeout()
		return
	}

	this.logoutAtTimestamp = null
	this.logout()
	return
}

#3

Thanks. Unfortunately these don’t appear to work in Capacitor.
Also I can’t use plugins as the webview in the device is too old.


#4

For anyone else looking at this @ScatchCTO’s solution works perfectly with Cordova.