javascript - Chat application polling -


i'm working on chat application, polls server @ timeout. timeout increases if, on time, there hasn't been recent activity. function loadnew() performs ajax call server, responds message data.

polltimeouttime = 500; function poll() {     polltimeout = settimeout(function(){         loadnew();         if (!new_messages_count) {             //increasing delay between polls no messages incoming maximum of 1 minute/60 seconds             if (polltimeouttime < 60000) polltimeouttime = polltimeouttime * 1.25;         }          else {             //reset delay between poll default of 0.5 seconds             polltimeouttime = 500;         }         poll();     },polltimeouttime); } 

the problem i'm having timeout function not wait function loadnew() complete, causes same poll sent twice or more if timeout lower time takes ajax call in function complete. server responds same data multiple times, leads duplicative display of messages in chat.

is there way make timeout trigger after loadnew() has finished fetching , displaying data?

edit: after using @brad m's answer, doesn't duplicate messages anymore. still have way call poll after user submits message, new message displayed immediately. interfere timeout set in loadnew(), cause messages duplicated again. think of way working?

without seeing loadnew function, easy fix might change function return ajax call (return $.ajax({...});) , change code posted this:

polltimeouttime = 500; function poll() {     polltimeout = settimeout(function () {         loadnew().done(function (result) {             if (!new_messages_count) {                 //increasing delay between polls no messages incoming maximum of 1 minute/60 seconds                 if (polltimeouttime < 60000) polltimeouttime = polltimeouttime * 1.25;             } else {                 //reset delay between poll default of 0.5 seconds                 polltimeouttime = 500;             }             poll();         });     }, polltimeouttime); } 

Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -