简体   繁体   中英

setInterval when new content is added

Possible a too broad question but i'll ask it anyways..

So I've made a chat application of my own php knowledge i got it too work however since im setting an interval to display my messages ever 10th second it steals a lot of bandwidth. So i was wondering...

  • Is there a way to setInterval whenever new messages is added on my database?
  • Or perhaps any other way some of you know that i should approach this problem?

Here is what I've come up with so far

<?php 
include "connect.php";
$query = "SELECT * FROM messages ORDER BY id ASC";
$result = $con->query($query);
if($result){

while($row = $result->fetch_object()) 
{   
    echo '<div id = "hehe">';
    echo '<div class = "userpic"><img src = "'.$row->userpic.'" class = "userpic"></div>';
    echo "<ul id = 'rutor'>";
    if (isset($row->displayname) && !empty($row->displayname)) {
        echo '<li class = "userlada">'.$row->displayname. "</li>";
    }
    else{
        echo '<li class = "userlada">'.$row->username. "</li>";
    }
    echo '<li class = "usertext">'.$row->message. "</li>";
    echo "</ul>";
    echo "</div>";
    }       
}
?>

My interval function to see the messages

setInterval(function() {
$( ".chatMessages" ).load( "getMeddelanden.php" );
}, 10000); 

Is there a way to setInterval whenever new messages is added on my database?

To inform the client whenever a new message is added to your database (server), you would need to make use of WebSocket to push the data to client-side.

What setInterval does is known as polling, where it repeatedly calls the server to see if a new message has been added, and if so, then retrieves it.

Or perhaps any other way some of you know that i should approach this problem?

To my knowledge, using WebSocket is the best way to go about it. There are technologies also available that you can use to make your work easier, such as socket.io , PubNub & MQTT .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM