Anonymous javascript polling function does not trigger setTimeout ajax call immediately -
this question has answer here:
- javascript ajax setinterval delay 3 answers
i have anonymous polling function has settimeout kick off ajax call every 30 seconds. however, anonymous function kick off reason ajax call not kick off immediately, starts after 30 seconds. missing calling trigger right away?
(function poll() { console.log('polling called'); settimeout(function () { $.ajax({ url: "/server/call", type: 'get', datatype: "json", timeout: 30000, success: function (data) { var currentdate = new date(); var datetime = "last sync: " + currentdate.getdate() + "/" + (currentdate.getmonth() + 1) + "/" + currentdate.getfullyear() + " @ " + currentdate.gethours() + ":" + currentdate.getminutes() + ":" + currentdate.getseconds(); console.log(datetime); console.log('call successful at: ' + datetime); } }); }, 30000); })();
the logging starts off after 30 seconds , not right away. thanks
that not remotely settimeout()
does. settimeout()
calls function, once, , after given time has expired.
setinterval()
close want, calls function first time after interval has expired once.
what need this:
const everythree = () => $.ajax({ url: "/server/call", type: 'get', ... everythree(); setinterval(everythree, 3000);
if don't using setinterval()
, can same thing manually:
const everythree = () => { settimeout(everythree, 3000); $.ajax({ url: "/server/call", type: 'get', ... everythree();
if suspect ajax call might run long, following:
const everythree = () => $.ajax({ url: "/server/call", type: 'get', ... }) .always(() => settimeout(everythree, 3000)); everythree();
this make next ajax call 3 seconds after previous 1 has succeeded, failed, or timed-out.
edit:
if don't have const
or =>
("fat-arrow") in environment, choices are
- make
var
,function
. inferior in many ways, universally available. - use transpiler babel , advantages of modern language (constants, easy anonymous functions, deconstruction, array-spreading), @ cost of slight increase in complexity in operational environment.
Comments
Post a Comment