VL53L0X Range Detector stops detecting

I am trying to use a VL53L0X to detect the salt level in my water softener, which is a bit unacessible. However after a relatively short time the sensor (or the code) stops changing and output freezes. Anyone had similar experience. Using an ESP8266-01 as monitor and control. Webserver to look at level.

Compiles, works OK for a bit (sinric is to alarm status to Alexa), then measurement freezes.

/*
  GPIO0 -> SDA pin of the I2C port
  GPIO2 -> SCL pin of the I2C port
* */
#define MyApiKey "xxxxxxxxxxx"
#define MyDeviceID "xxxxxxxxxx"
#define MySSID "xxxxxxxxxxxx"
#define MyWifiPassword "xxxxxxxxxxxxx"
const char* hostName = "Softener_Salt";
#define API_ENDPOINT "http://sinric.com"
//#define serialActive   //switches serial monitoring on/off

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsClient.h>
#include <ArduinoJson.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <StreamString.h>
#include "Adafruit_VL53L0X.h"

ESP8266WiFiMulti WiFiMulti;
WebSocketsClient webSocket;
WiFiClient client;

Adafruit_VL53L0X lox = Adafruit_VL53L0X();

uint64_t heartbeatTimestamp = 0;
bool isConnected = false;
bool alarmState = 0;
bool oldalarmState = 0;

ESP8266WebServer server(80);

unsigned long timer;
unsigned int distance;

String webPage1 = "";
String webPage2 = "";
String webPage3 = "";


void turnOff(String deviceId) {
 if (deviceId == MyDeviceID) // Device ID of first device
 {
#ifdef serialActive
   Serial.print("Turn off Device ID: "); Serial.println(deviceId);
#endif
 }
}
void turnOn(String deviceId) {
 if (deviceId == MyDeviceID) // Device ID of first device
 {
#ifdef serialActive
   Serial.print("Turn on device id: "); Serial.println(deviceId);
#endif
 }
}


void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
 switch (type) {
   case WStype_DISCONNECTED:
     isConnected = false;
#ifdef serialActive
     Serial.printf("[WSc] Webservice disconnected from sinric.com!\n");
#endif
     break;
   case WStype_CONNECTED: {
       isConnected = true;
#ifdef serialActive
       Serial.printf("[WSc] Service connected to sinric.com at url: %s\n", payload);
       Serial.printf("Waiting for commands from sinric.com ...\n");
#endif
     }
     break;
   case WStype_TEXT: {
#ifdef serialActive
       Serial.printf("[WSc] get text: %s\n", payload);
#endif
#if ARDUINOJSON_VERSION_MAJOR == 5
       DynamicJsonBuffer jsonBuffer;
       JsonObject& json = jsonBuffer.parseObject((char*)payload);
#endif
#if ARDUINOJSON_VERSION_MAJOR == 6
       DynamicJsonDocument json(1024);
       deserializeJson(json, (char*) payload);
#endif
       String deviceId = json ["deviceId"];
       String action = json ["action"];

       if (action == "setPowerState") { // Switch or Light
         String value = json ["value"];
         if (value == "ON") {
           turnOn(deviceId);
         } else {
           turnOff(deviceId);
         }
       }
       else if (action == "test") {
#ifdef serialActive
         Serial.println("[WSc] received test command from sinric.com");
#endif
       }
     }
     break;
   case WStype_BIN:
#ifdef serialActive
     Serial.printf("[WSc] get binary length: %u\n", length);
#endif
     break;
   default: break;
 }
}

void setPowerStateOnServer(String deviceId, String value) {

#if ARDUINOJSON_VERSION_MAJOR == 5
 DynamicJsonBuffer jsonBuffer;
 JsonObject& root = jsonBuffer.createObject();
#endif
#if ARDUINOJSON_VERSION_MAJOR == 6
 DynamicJsonDocument root(1024);
#endif

 root["deviceId"] = deviceId;
 root["action"] = "setPowerState";
 root["value"] = value;
 StreamString databuf;
#if ARDUINOJSON_VERSION_MAJOR == 5
 root.printTo(databuf);
#endif
#if ARDUINOJSON_VERSION_MAJOR == 6
 serializeJson(root, databuf);
#endif
 webSocket.sendTXT(databuf);
}


void setup() {
#ifdef serialActive
 Serial.begin(115200);
 delay(5000);
#endif

 //I2C stuff
 Wire.begin(0, 2); // (SDA, SCL)
 delay(500);

 WiFiMulti.addAP(MySSID, MyWifiPassword);
#ifdef serialActive
 Serial.println();
 Serial.print("Connecting to Wifi: "); Serial.println(MySSID);
#endif

 // Waiting for Wifi connect
 while (WiFiMulti.run() != WL_CONNECTED) {
   delay(500);
#ifdef serialActive
   Serial.print(".");
#endif
 }
 if (WiFiMulti.run() == WL_CONNECTED) {
#ifdef serialActive
   Serial.println("");
   Serial.print("WiFi connected. "); Serial.print("IP address: ");
   Serial.println(WiFi.localIP());
#endif
 }

 // server address, port and URL
 webSocket.begin("iot.sinric.com", 80, "/");

 // event handler
 webSocket.onEvent(webSocketEvent);
 webSocket.setAuthorization("apikey", MyApiKey);

 // try again every 5000ms if connection has failed
 webSocket.setReconnectInterval(5000);   // If you see 'class WebSocketsClient' has no member named 'setReconnectInterval' error update arduinoWebSockets

 webPage1 += "<head><title>";
 webPage1 += hostName;
 webPage1 += "</title><meta http-equiv='refresh' content='5'></head>";
 webPage1 += "<meta name = \"viewport\" content = \"width = device-width\">";
 webPage1 += "
<body bgcolor=\"#E6E6FA\">
<h1 align=center>";
 webPage1 += hostName;
 webPage1 += "</h1>
";

 server.on("/", []() {
   server.send(200, "text/html", webPage1 + webPage2 + webPage3);
 });

 server.begin();

 if (!lox.begin()) {
#ifdef serialActive
   Serial.println(F("Failed to boot VL53L0X"));
#endif
   while (1);
 };
 webPage3 = "</body>";
}

void loop() {
 webSocket.loop();
 server.handleClient();

 VL53L0X_RangingMeasurementData_t measure;
 lox.rangingTest(&measure, false); // pass in 'true' to get debug data printout!
 if (measure.RangeMilliMeter > distance + 10 || measure.RangeMilliMeter < distance - 10)
   distance = measure.RangeMilliMeter;

 if (millis() >= timer + 3000) {
   timer = millis();

   if (distance < 100) {
     webPage2 =  "<p align=center><button style='width:100px;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;'></button></p>";
   } else if (distance < 200) {
     webPage2 =  "<p align=center><button style='width:100px;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;'></button></p>";
   } else if (distance < 300) {
     webPage2 =  "<p align=center><button style='width:100px;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;'></button></p>";
   } else if (distance < 400) {
     webPage2 =  "<p align=center><button style='width:100px;height:20px;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;'></button></p>";
   } else {
     webPage2 =  "<p align=center><button style='width:100px;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;'></button></p>";
     webPage2 += "<p align=center><button style='width:100px;'></button></p>";

   }

   webPage2 += "<p font-size:18px; align=center><strong>";
   webPage2 += distance;
   webPage2 += "  mm</strong></p>";

   if (distance < 500) {
     alarmState = false;
   } else {
     alarmState = true;
   }

# ifdef serialActive
   Serial.print("Distance (mm): "); Serial.print(measure.RangeMilliMeter); Serial.print(" AlarmState: "); Serial.println(alarmState);
# endif

   if (oldalarmState != alarmState )
     if (alarmState)
       setPowerStateOnServer(MyDeviceID, "ON");
     else
       setPowerStateOnServer(MyDeviceID, "OFF");
   oldalarmState = alarmState;
 }

 delay(1000);
}

My first suspicion would be the delay() in your loop. Using delay is generally a bad idea but is especially bad when using communication stacks.

Rewrite loop() to call everything using timers with different intervals and make the loop() function run as often as possible. This will also allow you to extend the sketch without affecting the rest of the system too much.
e.g. call the webSocket.loop at least every 100ms for a start maybe even every 10ms. Other things like your sensor depend on your application.

The second part is your use of setup(). Setup is OK for demo examples but generally you should look into having your code run from loop. This will allow you to detect issue and restarting peripherals like your network when necessary. I like to use state machines based on switch/case statements. If I detect an issue e.g. the connection being lost, I close everything related to WiFi and restart. The rest of the system continues to run during that time.

To avoid having a very big loop function I create task functions and call them from loop. Each task handles on major part of the sketch and handles its own timing. I can call them as often as I want. The task itself will just return when nothing needs to be done. The task functions will not use delay(), while () or other code that stops/waits.