ESP32 WebServer Library -enableDelay()

Home / References / ESP32 Library / WebServer Library

Description

The enableDelay() method is used to enable or disable a small delay in the ESP32 WebServer’s client handling loop. This method controls whether the server introduces a 1-millisecond delay when no clients are available for processing, which helps prevent excessive CPU usage and allows other tasks to run. By default, the delay is enabled (true), which is recommended for most applications. Disabling the delay can be useful for performance testing, debugging timing-sensitive applications, or when you need maximum server responsiveness at the cost of higher CPU usage. This method is particularly valuable for developers who need to fine-tune server performance or test different timing behaviors in their applications.


Syntax and Usage

The enableDelay() method has a simple syntax:

  • Enable delay: server.enableDelay(true) – Enables the 1ms delay when no clients are available (default behavior, recommended for most applications).
  • Disable delay: server.enableDelay(false) – Disables the delay for maximum responsiveness but higher CPU usage.

For practical applications and examples of this method, please consult the “Example Code” section on this page. This section provides comprehensive guidance to help you better understand and apply the method effectively.

This page is part of the Comprehensive Guide to the ESP32 Arduino Core Library, accessible on AvantMaker.com.


Arguments

  • value (boolean) – A boolean value that determines whether to enable or disable the delay. true enables the delay (default), false disables it.

Return Value

The enableDelay() method does not return any value (void return type). The method configures the WebServer internally to either include or exclude the delay in its client handling loop.


Example Code

Performance Testing Server with Configurable Delay

This example demonstrates how to use enableDelay() for performance testing and optimization. The server provides endpoints to enable/disable delay and monitor performance metrics, making it ideal for comparing server behavior under different configurations.

How to use this example: Upload this code to your ESP32 and replace the WiFi credentials. After connecting, use these endpoints: http://ESP32_IP/ for the main interface, http://ESP32_IP/enable-delay to enable delay, http://ESP32_IP/disable-delay to disable delay, and http://ESP32_IP/status to check current configuration and performance metrics. Test with tools like ab -n 100 -c 10 http://ESP32_IP/api to benchmark performance differences between enabled and disabled delay modes.

/*
 * Author: Avant Maker
 * Date: June 18, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates how to use enableDelay() for performance
 * testing and optimization. The server provides endpoints to enable/disable
 * delay and monitor performance metrics, making it ideal for comparing server
 * behavior under different configurations.
 *
 * How to use this example:
 * Upload this code to your ESP32 and replace the WiFi credentials.
 * After connecting, use these endpoints: http://ESP32_IP/ for the main interface,
 * http://ESP32_IP/enable-delay to enable delay, http://ESP32_IP/disable-delay to
 * disable delay, and http://ESP32_IP/status to check current configuration and
 * performance metrics. Test with tools like ab -n 1000 -c 10 http://ESP32_IP/api to
 * benchmark performance differences between enabled and disabled delay modes.
 *
 * Code Source:
 * This example code is sourced from the Comprehensive Guide
 * to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
 * For additional code examples and in-depth documentation related to
 * the ESP32 Arduino Core Library, please visit:
 *
 * https://avantmaker.com/home/all-about-esp32-arduino-core-library/
 *
 * AvantMaker.com, your premier destination for all things
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated
 * to empowering makers, learners, and enthusiasts with
 * the resources they need to bring their nnovative ideas to life.
 */

#include <WiFi.h>
#include <WebServer.h>

const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";

WebServer server(80);

// Performance tracking variables
unsigned long requestCount = 0;
unsigned long startTime = 0;
bool delayEnabled = true;

void handleRoot() {
  String html = "<html><head><title>ESP32 Delay Configuration</title></head><body>";
  html += "<h1>ESP32 WebServer Delay Control</h1>";
  html += "<p>Current delay status: <strong>" + String(delayEnabled ? "ENABLED" : "DISABLED") + "</strong></p>";
  html += "<p>Requests handled: " + String(requestCount) + "</p>";
  
  if (startTime > 0) {
    unsigned long uptime = (millis() - startTime) / 1000;
    float requestsPerSecond = requestCount / (float)uptime;
    html += "<p>Uptime: " + String(uptime) + " seconds</p>";
    html += "<p>Average requests/second: " + String(requestsPerSecond, 2) + "</p>";
  }
  
  html += "<h2>Controls</h2>";
  html += "<p><a href='/enable-delay'>Enable Delay</a> (Better CPU usage)</p>";
  html += "<p><a href='/disable-delay'>Disable Delay</a> (Maximum responsiveness)</p>";
  html += "<p><a href='/reset-stats'>Reset Statistics</a></p>";
  html += "<h2>Test Endpoints</h2>";
  html += "<p><a href='/api'>Test API Endpoint</a></p>";
  html += "<p><a href='/status'>JSON Status</a></p>";
  html += "</body></html>";
  
  server.send(200, "text/html", html);
  requestCount++;
}

void handleEnableDelay() {
  delayEnabled = true;
  server.enableDelay(true);
  
  String message = "Delay ENABLED\n\n";
  message += "This enables a 1ms delay when no clients are available.\n";
  message += "Benefits:\n";
  message += "- Reduces CPU usage\n";
  message += "- Allows other tasks to run\n";
  message += "- Recommended for most applications\n\n";
  message += "Go back to: " + String("http://") + WiFi.localIP().toString();
  
  server.send(200, "text/plain", message);
  requestCount++;
  
  Serial.println("Delay enabled - CPU friendly mode");
}

void handleDisableDelay() {
  delayEnabled = false;
  server.enableDelay(false);
  
  String message = "Delay DISABLED\n\n";
  message += "This removes the 1ms delay when no clients are available.\n";
  message += "Benefits:\n";
  message += "- Maximum server responsiveness\n";
  message += "- Useful for performance testing\n";
  message += "Drawbacks:\n";
  message += "- Higher CPU usage\n";
  message += "- May affect other tasks\n\n";
  message += "Go back to: " + String("http://") + WiFi.localIP().toString();
  
  server.send(200, "text/plain", message);
  requestCount++;
  
  Serial.println("Delay disabled - maximum performance mode");
}

void handleStatus() {
  String json = "{";
  json += "\"delayEnabled\":" + String(delayEnabled ? "true" : "false") + ",";
  json += "\"requestCount\":" + String(requestCount) + ",";
  json += "\"freeHeap\":" + String(ESP.getFreeHeap()) + ",";
  json += "\"uptime\":" + String(millis()) + ",";
  json += "\"cpuFreq\":" + String(ESP.getCpuFreqMHz()) + ",";
  json += "\"chipModel\":\"" + String(ESP.getChipModel()) + "\",";
  json += "\"flashSize\":" + String(ESP.getFlashChipSize()) + ",";
  json += "\"wifiRSSI\":" + String(WiFi.RSSI());
  json += "}";
  
  server.send(200, "application/json", json);
  requestCount++;
}

void handleAPI() {
  // Simple API endpoint for performance testing
  String response = "OK";
  server.send(200, "text/plain", response);
  requestCount++;
}

void handleResetStats() {
  requestCount = 0;
  startTime = millis();
  
  server.send(200, "text/plain", "Statistics reset!\nGo back to: http://" + WiFi.localIP().toString());
  
  Serial.println("Statistics reset");
}

void setup() {
  Serial.begin(115200);
  
  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  
  Serial.println("WiFi connected!");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  
  // Initialize performance tracking
  startTime = millis();
  
  // Configure server with delay enabled by default
  server.enableDelay(true);
  
  // Set up route handlers
  server.on("/", handleRoot);
  server.on("/enable-delay", handleEnableDelay);
  server.on("/disable-delay", handleDisableDelay);  
  server.on("/status", handleStatus);
  server.on("/api", handleAPI);
  server.on("/reset-stats", handleResetStats);
  
  // Start server
  server.begin();
  Serial.println("HTTP server started with delay enabled (default)");
  Serial.println("Use the web interface to enable/disable delay and monitor performance");
}

void loop() {
  server.handleClient();
  
  // Optional: Print periodic status to Serial
  static unsigned long lastPrint = 0;
  if (millis() - lastPrint > 30000) { // Every 30 seconds
    lastPrint = millis();
    Serial.println("Status - Delay: " + String(delayEnabled ? "ON" : "OFF") + 
                   ", Requests: " + String(requestCount) + 
                   ", Free Heap: " + String(ESP.getFreeHeap()));
  }
}

For more ESP32 development resources and tutorials, visit AvantMaker.com

For more ESP32 development resources and tutorials, visit the All About ESP32 Resources Hub on  AvantMaker.com

error: Content is protected !!