让函数每5秒运行一次

Problems getting function to run every 5 seconds

本文关键字:一次 运行 函数 5秒      更新时间:2023-09-26

我正在尝试创建一个通知系统,每当在数据库中创建新条目时,用户就会看到通知。对于它自己,脚本循环遍历mysql表,直到检测到新条目,然后停止循环并显示通知。

我的意图是修改脚本,以便在通知之后,当检测到新记录时,函数(check())应该每五秒召回一次。

我的问题是,当我把脚本在一个基于时间的循环(5秒间隔),循环似乎无限期地运行,即使插入新的记录。

 <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>

<?php
$echo_time = time();
$interval = 5;
while(true){
 if ($echo_time + $interval >= time()){
  check();
  echo "$interval seconds have passed...";
  $echo_time = time(); // set up timestamp for next interval
}
// other uninterrupted code goes here.

function check()
{
 $timeStart = time();
 $today = date("Y-m-d H:i:s");       
 // Create connection
 $con = mysqli_connect('localhost','root','root','test');
 // Check connection
 if (mysqli_connect_errno($con))
 die ('Failed to connect to MySQL: ' . mysqli_connect_error() );
 // select where item is new
 if(isset($_POST['timestamp'])){
    $timestamp = $_POST['timestamp'];
 }else
 {
  // get current database time
  $row = mysqli_fetch_assoc(mysqli_query($con,'SELECT now() as now'));
  $timestamp = $row['now'];
 }
 $sql = "SELECT * FROM records WHERE insertDate > '$timestamp'";
 $newData = false;
 $notifications = array();
 // loop while there is no new data and is running for less than 20 seconds
 while(!$newData && (time()-$timeStart)<20){
  // check for new data
  $result = mysqli_query($con,$sql);
  while($row = mysqli_fetch_assoc($result)){
     $notifications[] = $row;
     $newData = true;
     echo "<script>
        $(document).ready(function() {
        $.sticky('The page has loaded!');
         var callnotification = function(){
         $.sticky('<b>A new Invoice has arrived!</b>');
         }
        callnotification;
       });
      </script>";
    }
   }
 // get current database time
 $row = mysqli_fetch_assoc(mysqli_query($con,'SELECT now() as now'));
 $timestamp = $row['now'];
 mysqli_close($con);
 }

可以使用"setTimeout"函数来实现

for example:

var checkForNotification = function(){
   // ajax call to a function which check for a new notification
};
setTimeout(checkForNotification, 5000);