Javascript: multiple events, one ajax request -


i'm new js , i'm trying think of best way design asynchronous interaction in application i'm working on.

i've got list of records related live api-backed data. show user list of these records, , user can select specific records want see more information about. load additional data api via ajax call.

to make more real world example, let's have list of stocks. i've got name , yesterday's closing price each stock. there's check box next each stock name, , if user checks box plots historic price of stock past year on graph.

when user selects 1 stock in way, behavior simple. send 1 api request historical data 1 stock, , plot on graph.

however, user might select bunch of stocks @ once, or in rapid succesion. don't want fire 10 or 20 or 50 requests back-to-back, want make 1 request 10 or 20 or 50 stock histories.

let's application has event listener looks stock history when check box toggled, this:

$('input.stock_toggle').change( function(event){   var symbol = $(this).data('symbol');   lookupstockhistory(symbol); }); 

how define lookupstockhistory function, or other kind of event listener etc., wait second , pool events came in send single request instead of firing many times in row?

var lookupstockhistory = (function () { "use strict"; var qeue = [], timeouthandler = null, timeouttime = 1000,     sendcall = function () {         //process qeue array , trigger ajax call         //and clean qeue         qeue = [];     },     add = function (symbol) {         if (timeouthandler) {             cleartimeout(timeouthandler);             timeouthandler = null;         }         qeue.push(symbol);         timeouthandler = settimeout(sendcall, timeouttime);     }; return add;}()); 

to trigger call lookupstockhistory(symbol). gather symbol array processed after 1 second since last call


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -