connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT count as c FROM count WHERE id = $iidd"; $result = $conn->query($sql); $row = $result->fetch_assoc(); if ($row==null || $row["c"]==null) { //echo "new counter"; $visits = 1; } else { $visits = $row["c"]; } $conn->close(); return $visits; } $a = array(); $a["oldcount"] = getCount($_POST["iid"]); $sleep = rand(1,60); // this is the core of long polling. Essentially a sleep loop // where check for something to report. In some sense the "polling" // then occurs all on the server side. for ($i=0; $i<$sleep; $i++) { $a["count"] = getCount($_POST["iid"]); if ($a["count"] != $a["oldcount"]) { $a["actualwait"]=$i; break; } sleep(1); } $a["time"]=date(DATE_RFC2822); $a["sleep"]=$sleep; // return JSON just because I can echo json_encode($a); ?>