title: How to use ajax and setInterval on an ESP8266 HTML webpage served with Arduino
body: <p>I have been recently learning how to program in <strong>Arduino</strong> to host a  HTML/CSS/Javascript webpage on an <strong>Adafruit HUZZAH ESP8266 breakout</strong> chip, so please forgive me if my methods here are completely off. </p>
  
  <p>I'm currently trying to get a value to automatically update via <strong>ajax</strong> with a javascript function that is using <strong>setInterval</strong> to run every five seconds. And while it does update the value at least one time, it takes far longer than five seconds to do so, and then it never updates the value again. </p>
  
  <p>Please let me know what you think of the way I'm currently trying to implement this, and if I'm way off the mark? To help you navigate the key functions are <strong>loadNum()</strong> and <strong>sendNum()</strong>; and the variable that's incrementing is <strong>testNumPart2</strong> (there's also more code on here as well that uses a button to turn an LED on/off). </p>
  
  <p>Thanks!</p>
  
  <pre><code>#include &lt;ESP8266WiFi.h&gt;
  
  #define LED_PIN  15  // This example assumes you have a LED connected to pin 13
  
  const char* ssid = "REDACTED";
  const char* password = "REDACTED";
  
  // Create an instance of the server
  // specify the port to listen on as an argument
  WiFiServer server(80);
  
  void setup() {
    Serial.begin(115200);
    delay(10);
  
    // prepare GPIO2
    pinMode(LED_PIN, OUTPUT);
    //digitalWrite(2, 0);
  
    // Connect to WiFi network
    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);
  
    WiFi.begin(ssid, password);
  
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    Serial.println("");
    Serial.println("WiFi connected");
  
    // Start the server
    server.begin();
    Serial.println("Server started");
  
    // Print the IP address
    Serial.println(WiFi.localIP());
  }
  
  void loop() {
    // Check if a client has connected
    WiFiClient client = server.available();
    if (client) {
      Serial.println("new client");
      // an http request ends with a blank line
  boolean currentLineIsBlank = true;
  String currentLine = "";
  String LEDstatus = "off";
  
  String testNumPart1 = "document.getElementById('demo').innerHTML = ";
  int testNumPart2 = 23; 
  
  String testNum = testNumPart1 + testNumPart2; 
  
  //Serial.print("TEST: ");
  //Serial.println(testNum);
  
  while (client.connected()) {
    if (client.available()) {
      char c = client.read();
      Serial.write(c);
  
      testNumPart2++;
  
      testNum = testNumPart1 + testNumPart2; 
  
      // if you've gotten to the end of the line (received a newline
      // character) and the line is blank, the http request has ended,
      // so you can send a reply
      if (c == '\n' &amp;&amp; currentLineIsBlank) {
        // send a standard http response header
        client.println("HTTP/1.1 200 OK");
        client.println("Content-Type: text/html");
        client.println("Connection: close");  // the connection will be closed after completion of the response
        //client.println("Refresh: 5");  // refresh the page automatically every 5 sec
        client.println();
        client.println("&lt;!DOCTYPE HTML&gt;");
        client.println("&lt;html&gt;");
          client.println("&lt;head&gt;");
              client.println("&lt;title&gt;Adafruit HUZZAH ESP8266&lt;/title&gt;");
              client.println("&lt;style type='text/css'&gt;");
  
                  //Styles for on/off switch
                  client.println(".onoffswitch { position: relative; width: 90px; -webkit-user-select:none; -moz-user-select:none; -ms-user-select: none; }");
                  client.println(".onoffswitch-checkbox { display: none; }");
                  client.println(".onoffswitch-label { display: block; overflow: hidden; cursor: pointer; border: 2px solid #999999; border-radius: 20px; }");
                  client.println(".onoffswitch-inner { display: block; width: 200%; margin-left: -100%; transition: margin 0.3s ease-in 0s;}");
                  client.println(".onoffswitch-inner:before, .onoffswitch-inner:after { display: block; float: left; width: 50%; height: 30px; padding: 0; line-height: 30px; font-size: 14px; color: white; font-family: Trebuchet, Arial, sans-serif; font-weight: bold; box-sizing: border-box; }");
                  client.println(".onoffswitch-inner:before { content: 'ON'; padding-left: 10px; background-color: #34A7C1; color: #FFFFFF; }");
                  client.println(".onoffswitch-inner:after { content: 'OFF'; padding-right: 10px; background-color: #EEEEEE; color: #999999; text-align: right; }");
                  client.println(".onoffswitch-switch { display: block; width: 18px; margin: 6px; background: #FFFFFF; position: absolute; top: 0; bottom: 0; right: 56px; border: 2px solid #999999; border-radius: 20px; transition: all 0.3s ease-in 0s; }");
                  client.println(".onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-inner { margin-left: 0; }");
                  client.println(".onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-switch { right: 0px; }");
              client.println("&lt;/style&gt;");
  
              //Javascript Function
              client.println("&lt;script&gt;");
                  client.println("function LEDswitch(){");
                      client.println("var LEDswitchCheck = document.getElementById('myonoffswitch').checked;");
  
                      client.println("if(LEDswitchCheck){");
                          client.println("window.location.href = '/H';");
                      client.println("}");
                      client.println("else {");
                          client.println("window.location.href = '/L';");
                      client.println("}");
                  client.println("}");
                  client.println("function loadNum() {");
                      client.println("setInterval(sendNum, 5000);");
                  client.println("}");
                  client.println("function sendNum() {");
                      client.println("var request = new XMLHttpRequest();");
                      client.println("request.onreadystatechange = function() {");
                          client.println("if (this.readyState == 4) {");
                              client.println("if (this.status == 200) {");
                                  client.println(testNum);
                              client.println("}");
                          client.println("}");
                      client.println("};");
                      client.println("request.open('GET', '', true);");
                      client.println("request.send();");
                  client.println("}");
              client.println("&lt;/script&gt;");
  
          client.println("&lt;/head&gt;");
          client.println("&lt;body style='background-color:#558C89;' onload=\"loadNum()\"&gt;");
              client.println("&lt;div style='background-color:#74AFAD;'&gt;");
                  client.println("&lt;h1 style='text-decoration: underline;'&gt;Adafruit HUZZAH ESP8266&lt;/h1&gt;");
              client.println("&lt;/div&gt;");
  
      }
      if (c == '\n') {
        // you're starting a new line
        currentLineIsBlank = true;
  
        // if the current line is blank, you got two newline characters in a row.
        // that's the end of the client HTTP request, so send a response:
        if (currentLine.length() == 0) {
          client.println("&lt;div style='background-color:#74AFAD;'&gt;");
              client.println("&lt;h2 style='color: red;'&gt;LED Controls&lt;/h2&gt;");
  
          // The HTTP response ends with another blank line:
          client.println();
  
                          client.println("&lt;div class='onoffswitch'&gt;");
  
                              if (LEDstatus == "on") 
                              {
                                  client.println("&lt;input type='checkbox' name='onoffswitch' class='onoffswitch-checkbox' id='myonoffswitch' checked='checked' onclick='LEDswitch()'&gt;");
  
  
                              } //end if
                              else if(LEDstatus == "off")
                              {
                                  client.println("&lt;input type='checkbox' name='onoffswitch' class='onoffswitch-checkbox' id='myonoffswitch' onclick='LEDswitch()'&gt;");
                              } //end else
  
                              client.println("&lt;label class='onoffswitch-label' for='myonoffswitch'&gt;");
                                  client.println("&lt;span class='onoffswitch-inner'&gt;&lt;/span&gt;");
                                  client.println("&lt;span class='onoffswitch-switch'&gt;&lt;/span&gt;");
                              client.println("&lt;/label&gt;");
                          client.println("&lt;/div&gt;");
                      client.println("&lt;/div&gt;"); 
                      client.println("&lt;div style='background-color:#74AFAD;'&gt;");
                          client.println("&lt;h2 style='color: green;'&gt;Num Refresh Test&lt;/h2&gt;");
                          client.println("&lt;div id='demo'&gt;&lt;h2&gt;Let AJAX change this text&lt;/h2&gt;&lt;/div&gt;");
                          //client.println("&lt;button type='button' onclick='loadNum()'&gt;Change Content&lt;/button&gt;");
                      client.println("&lt;/div&gt;");
                  client.println("&lt;/div&gt;");
              client.println("&lt;/body&gt;");
          client.println("&lt;/html&gt;");
          break;
        } //end if
  
        else
        {
            currentLine = ""; 
        } //end else
      }
      else if (c != '\r') {
        // you've gotten a character on the current line
        currentLineIsBlank = false;
  
        currentLine += c;
      }
  
      // Check to see if the client request was "GET /H" or "GET /L":
      if (currentLine.endsWith("GET /H")) {
        digitalWrite(LED_PIN, HIGH);               // GET /H turns the LED on
        LEDstatus = "on";
      } //end if (/H)
  
      if (currentLine.endsWith("GET /L")) {
        digitalWrite(LED_PIN, LOW);                // GET /L turns the LED off
        LEDstatus = "off";
      } //end if (/L)
  
    } //end if (client available)
  } //end while
  // give the web browser time to receive the data
  delay(1);
  
  // close the connection:
  client.stop();
  Serial.println("client disconnected");
  } //end if (client)
  } //end void loop
  </code></pre>