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:
- java-script sends request server using ajax
- if server has new message, responds new message
- if server doesn't have new message, doesn't return , request remains alive (still connected server waiting response)
- 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
- create request
- on
receiving content
, execute function (update chat box) and send request again - 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:
- creates request
- on receiving content, execute function (update chat box) and send request again
- 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
Post a Comment