Alexander Schurf
Alexander Schurf

Reputation: 85

how to stop code execution if the component is inactive in Nativescript Vue

My application should send data about the device every 5 seconds, but if I minimize the application and reopen it, or if I just go back to the page and go back, the code continues to run even in the background. When I open the application again, the function of sending data is superimposed on an already working function and the data leaves twice as often and so you can create a function indefinitely

How to solve this problem?

My method:

sendDeviceInfo(){
                console.log("1111");
                axios.post('', {
                    device: DeviceInfo.systemManufacturer() + ' ' +DeviceInfo.deviceName(),
                    deviceId: DeviceInfo.deviceId(),
                    appId: DeviceInfo.appVersion(),
                    email: this.email,
                    battery: DeviceInfo.batteryLevel(),
                    batteryCharging: DeviceInfo.isBatteryCharging() === true ? 1 : 0
                });
            }

And mounted:

this.sendDeviceInfo();
setInterval(this.sendDeviceInfo, 5000);

Upvotes: 0

Views: 944

Answers (1)

Tim VN
Tim VN

Reputation: 1193

You'll want to clear the interval when the component is destroyed. setInterval returns a reference you can use to clear it.

data: () => ({
    ...yourDataStuff,
    sendDeviceInfoInterval: null
}),

mounted() {
    this.sendDeviceInfoInterval = setInterval(this.sendDeviceInfo, 5000);
},

beforeDestroy() {
    clearInterval(this.sendDeviceInfoInterval);
}

Upvotes: 1

Related Questions