How To Use setInterval in PHP?

How To Use setInterval in PHP?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

The Fundamental Misconception of setInterval in PHP

You cannot use setInterval in PHP because it does not exist, and attempting to call a function repeatedly after a delay within a standard web request is fundamentally incompatible with how the language operates. Your goal is to display dynamic data—specifically post likes—on an HTML page without refreshing the browser. In JavaScript, this is achieved using setInterval, but porting that mental model directly to PHP will lead to broken code or infinite loops that crash your script.

The Synchronous Execution Model

PHP scripts are synchronous and blocking by default. When you execute a file like index.php, the server parses every line, executes every loop, queries the database, and renders the final HTML before sending the response back to the client. There is no background thread running while the user views the page waiting for five seconds to pass so it can run your code again.

If you wrap your logic in a sleep() function or try to simulate a timer, the entire HTTP request hangs until that time elapses. To a user visiting your site, this means a 5-second freeze where nothing happens. This is the exact opposite of the "setInterval" behavior you are looking for.

The Real Solution: AJAX and Polling

To achieve the effect of a JavaScript interval in PHP, you must decouple data fetching from page rendering. The standard architectural pattern for this involves two distinct endpoints:

  1. The Display Page: This loads once (e.g., index.php) and renders the static HTML structure.
  2. The Data Endpoint: A separate script (e.g., updates.php) that returns only raw JSON data. You use JavaScript's native setInterval to fetch this endpoint every few seconds, update the DOM elements, and leave the page state intact.

Here is how you would restructure the logic from your source material. First, ensure your database connection uses modern standards; your example relies on the deprecated mysql_* functions which were removed in PHP 7.0. You should migrate to mysqli or PDO immediately.

updates.php (The Data Endpoint)

<?php
header('Content-Type: application/json');
session_start(); // Handle authentication here, not via cookies directly in SQL

// Use prepared statements to prevent SQL injection
$pdo = new PDO("mysql:host=localhost;dbname=your_db", "username", "password");

$stmt = $pdo->prepare("SELECT * FROM posts WHERE name = :name");
$stmt->execute([':name' => $_SESSION['usename']]); // Or handle cookies securely

$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($data);
?>

index.php (The Display Page with JavaScript)

<!DOCTYPE html>
<html>
<head>
    <script>
        const updateInterval = 5000; // 5 seconds
        const userId = 'user123'; 

        function loadUpdates() {
            fetch('/updates.php')
                .then(response => response.json())
                .then(data => {
                    const likesContainer = document.getElementById('likes');
                    if (data.length > 0) {
                        // Logic to render likes based on data array
                        likesContainer.innerHTML = ''; 
                        data.forEach(post => {
                            const div = document.createElement('div');
                            div.id = 'likes';
                            div.textContent = post.likes;
                            likesContainer.appendChild(div);
                        });
                    }
                })
                .catch(error => console.error('Error fetching updates:', error));
        }

        // Start the interval after a brief delay to prevent flickering on load
        setTimeout(loadUpdates, 1000); 
        setInterval(loadUpdates, updateInterval);
    </script>
</head>
<body>
    <div id="likes"></div>
</body>
</html>

Why Not Keep the Script Running?

Your original request implies running a script "until it is aborted." In PHP, this usually suggests Cron jobs or long-running processes. While valid for backend tasks (like exporting CSVs), they are not suitable for updating a live web page's UI. A user cannot interact with a page that requires a full server restart to update its content.

Furthermore, your original Wall_Updates class contained significant security vulnerabilities. Using $_COOKIE['usename'] directly in a SQL query exposes you to SQL injection attacks. Even if you fix the syntax, passing untrusted input directly into mysql_query() is a critical failure that must be addressed before attempting any automation logic.

If you need persistent background processing for tasks unrelated to immediate UI updates, PHP's built-in scheduler or a queue system like Laravel Jobs (available at https://laravelcompany.com) would be the appropriate tool, not setInterval.

Our network