jquery - Repeatedly calling JavaScript function without getting a stackoverflow -


so little background on trying do:
trying create real time chat application uses ajax repeatedly check new messages on server.
difference here using long-polling technique works this:

  1. java-script sends request server using ajax
  2. if server has new message, responds new message
  3. if server doesn't have new message, doesn't return , request remains alive (still connected server waiting response)
  4. once server gets new message, responds new message request on hold/waiting response


what trying do

i confused on how write client-sided scipt. per description above, script should

  1. create request
  2. on receiving content, execute function (update chat box) and send request again
  3. on timeout, send request again , wait response till timeout


what have attempted

so script when in main page:

<script type="text/javascript">     $(document).ready(function() {         getmsg();     });      function getmsg() {         var time = math.floor(date.now() / 1000);          $.ajax({             url: "get_message.php?lastupdate=" + time,             type: "get",             datatype: "json",             timeout: 15000, //15 second timeout             success: function(response) {                 $('#chatbox').append("> " + response + "<br/>");                 getmsg();             },             error: function(x, t, m) {                 getmsg();             }         });     } </script> 


the problem

as see here, on error , success calling getmsg() function getmsg() function self. dont run risk of getting stackoverflow? mean of course going impossible since need huge number of recursions still feels bad programming method...

there alternative way script:

  1. creates request
  2. on receiving content, execute function (update chat box) and send request again
  3. on time out, restart function again

thanks spending time read this!

don't run risk of getting stack overflow?

short answer:

no.

long answer:

when call $.ajax, current instance of getmsg doesn't wait ajax request complete. binds event handlers have , says "alright, i'm done":

function getmsg() {     var time = math.floor(date.now() / 1000);      $.ajax({         // options     });      // alright, i'm done } 

so returns.

why?, ask. because "a" in ajax stands asynchronous. means when initiate ajax request, else can move on.

by time call getmsg in handlers, it's new instance not recursive. there never more 1 getmsg running. there's no recursion. no stack overflow. no problem.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -