Strange setTimeout clearing behaviour with jQuery AJAX - javascript

So, I'm trying to set a timeout on each request that is sent and work out if one is taking "too long". I'm watching the network tab and each request is well under 300ms, however 'too long' gets logged 6 times! (the number of requests I'm sending). Is there something I'm doing wrong with variables, setTimeouts or something?
var ajaxMonitor = {};
function timingStart() {
var url = arguments[2].url;
ajaxMonitor[url] = {};
ajaxMonitor[url].timer = setTimeout(function () {
console.log('too long');
}, 300);
}
function timingEnd() {
var url = arguments[2].url;
clearTimeout(ajaxMonitor[url].timer);
}
$(document).ajaxSend(timingStart);
$(document).ajaxComplete(timingEnd);

As pointed out in the comment it might be because you are calling the same url multiple times. If that is the case, one way to fix that problem is to clear the interval before setting it:
function timingStart() {
var url = arguments[2].url;
clear(url);
ajaxMonitor[url] = {};
ajaxMonitor[url].timer = setTimeout(function () {
console.log('too long');
}, 300);
}
function timingEnd() {
var url = arguments[2].url;
clear(url);
}
function clear(url) {
if(ajaxMonitor[url])
clearTimeout(ajaxMonitor[url].timer);
}
$(document).ajaxSend(timingStart);
$(document).ajaxComplete(timingEnd);

Related

my functions are mixed and the engine executing what ever he wants

so i was told to Present a loader to the user when a call is made to the server (indicating the server is calculating) Present an error to the user if the input number is more than 50, and do not send a server request Try passing the number 42 to the server. The server will send back an error, present this error to the user.
now what i did is everything besides the last error to present it to the user.
i have tried everything i could think of, and no matter what the user types, it displays both of the messages.
this is my code:
const clcBtn = document.getElementById("calcButton");
let clcInput = document.getElementById("calcInput");
const result = document.getElementById('paragraph');
const loader = document.getElementById('spinner');
const error = document.getElementById('error-message');
const serverError = document.getElementById('server-error');
clcBtn.addEventListener("click", calcFunc);
function numValidate(value) {
if(value > 50) {
return false;
}
return true;
}
function calcFunc() {
if (!numValidate (clcInput.value)) {
error.style.display = "block"
setTimeout(() => {
error.style.display = "none";
}, 5000);
console.error("Can't be larger than 50") // only bec it's a cool feature :D
return;
}
loader.classList.add("spinner-border");
fetch(`http://localhost:5050/fibonacci/${clcInput.value}`).then(function (response) {
return response.json().then(function (data) {
result.innerHTML = data.result;
});
});
setTimeout(() => {
loader.classList.remove("spinner-border");
}, 1000);
}
this is my code with what i have tried to add (on of the things i have tried.. this is the best output i could come with)
code:
// additional code to present to the user the error message if the input value is equal to 42.
clcBtn.addEventListener("click", errMsg);
function numValidateTwo(value) {
if(value === 42) {
return true;
}
return false;
}
function errMsg() {
if (!numValidateTwo (clcInput.value)) {
serverError.style.display = "block";
}
return;
}
a little bit more about what i am trying to achieve:
i want to present this error message to the user, whenever the input value is equal to 42.
is it related to async or callback? which i need to go through the lectures again.. but right now i need to solve this bec i have no time.
what did i do wrong ?
and how i can make it work?
can someone explain this to me?
thanks in advance!

Change the cells of a table in an interval time using OData model

I have this code and I need my table to show the first 10 patients and, after 10 seconds, show the next 10 without touching any button (automatically).
I'm looking for something similar to this: https://embed.plnkr.co/ioh85m5OtPmcvPHyl3Bg/
But with an OData model (as specified on my view and controller).
This is my view:
<Table id="tablaPacientes" items="{/EspCoSet}">
<columns>
<!-- ... -->
</columns>
<ColumnListItem>
<ObjectIdentifier title="{Bett}" />
<!-- ... -->
</ColumnListItem>
</Table>
This is my controller:
onInit: function () {
var oModel = this.getOwnerComponent().getModel("zctv");
this.getView().setModel(oModel);
},
onBeforeRendering: function () { // method to get the local IP because I need it for the OData
var ipAddress;
var RTCPeerConnection = window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
var self = this;
function grepSDP (sdp) {
var ip = /(192\.168\.(0|\d{0,3})\.(0|\d{0,3}))/i;
sdp.split('\r\n').forEach(function (line) {
if (line.match(ip)) {
ipAddress = line.match(ip)[0];
self.setIp(ipAddress);
}
});
}
if (RTCPeerConnection) {
(function () {
var rtc = new RTCPeerConnection({
iceServers: []
});
rtc.createDataChannel('', {
reliable: false
});
rtc.onicecandidate = function (evt) {
if (evt.candidate) {
grepSDP(evt.candidate.candidate);
}
};
rtc.createOffer(function (offerDesc) {
rtc.setLocalDescription(offerDesc);
}, function (e) {
console.log("Failed to get Ip address");
});
})();
}
},
setIp: function (ip) {
this.getView().byId("planta").bindElement({
path: "/CenTVSet('" + ip + "')"
});
var oModel = this.getView().getModel();
var that = this;
oModel.read("/CenTVSet('" + ip + "')", {
success: function (oData, oRes) {
var einri = oData.Einri;
var orgpf = oData.Orgpf;
var oTable = that.getView().byId("tablaPacientes");
var oBinding = oTable.getBinding("items");
var aFilters = [];
var filterO = new Filter("Orgna", sap.ui.model.FilterOperator.EQ, orgpf);
aFilters.push(filterO);
var filterE = new Filter("Einri", sap.ui.model.FilterOperator.EQ, einri);
aFilters.push(filterE);
oBinding.filter(aFilters);
}
});
}
I searched some functions like IntervalTrigger but I really don't know how can I use it for this example.
Here are some small samples:
OData V4: https://embed.plnkr.co/4zIAH7q2E0lngbyX
OData V2: https://embed.plnkr.co/rNa0TktXiQqSCGJV
startList: function(listBase, $skip, $top, restInfo) {
let startIndex = $skip;
let length = $top;
let totalSize;
(function repeat(that) {
const bindingInfo = Object.assign({ startIndex, length }, restInfo);
listBase.bindItems(bindingInfo);
listBase.data("repeater", event => {
totalSize = event.getParameter("total"); // $count value
startIndex += $top;
startIndex = startIndex < totalSize ? startIndex : 0;
setTimeout(() => repeat(that), 2000);
}).attachEventOnce("updateFinished", listBase.data("repeater"), that);
})(this);
},
stopList: function(listBase) {
listBase.detachEvent("updateFinished", listBase.data("repeater"), this);
},
The samples make use of startIndex and length in the list binding info which translates to $skip and $top system queries of the entity request URL. I.e. appending those system queries to the request URL (e.g. https://<host>/<service>/<EntitySet>?$skip=3&$top=3), should return the correct set of entities like this.
Additional options for the list binding info can be found in the UI5 documentation as I explained here.
JavaScript part
The interval is implemented with an IIFE (Immediately Invoked Function Expression) in combination with setTimeout instead of setInterval.
setInterval has the following disadvantages:
The callback is not immediately invoked. You'd have to wait 10 seconds first to trigger the 1st callback.
Does not wait for the data response to arrive. This may cause skipping a batch or showing it for a too short period of time because the delay simply continues regardless of the server response.
setTimeout instead offers a better control when the next batch should be requested.
You could bind you items using bindItems, pass skip,top parameters and wrap the whole thing in a setInterval
var iSkip = 0;
var iTop = 10;
setInterval(function() {
table.bindItems("/EspCoSet", {
urlParameters: {
"$skip": iSkip.toString() // Get first 10 entries
"$top": iTop.toString()
},
success: fuction (oData) {
iSkip = iTop; // Update iSkip and iTop to get the next set
iTop+= 10;
}
...
}, 10000); // Each 10 seconds
)
Almost the same thing, just use oModel.read to read the entities into you viewModel.allEntities, bind your table to the viewModel.shownEntities and use a setInterval to get the next 10 from allEntities to update shownEntities.

javascript function move to webworker

I have function:
function addModel() {
var values = new Array();
var $input = $('input[type=\'text\']');
var error = 0;
$input.each(function() {
$(this).removeClass('double-error');
var that = this;
if (that.value!='') {
values[that.value] = 0;
$('input[type=\'text\']').each(function() {
if (this.value == that.value) {
values[that.value]++;
}
});
}
});
$input.each(function(key) {
if (values[this.value]>1) {
//error++;
var name = this.value;
var product_model = $(this).parent().parent().find('.product-model').text();
var m = product_model.toLowerCase().areplace(search,replace);
$(this).parent().find('input[type=\'text\']').val(name + '-' + m);
}
});
return error <= 0; //return error > 0 ? false : true;
}
where are a lot of inputs to recheck... up to 50000. Usually are about 5000 to 20000 inputs. Of course browsers are freezing... How to move this function to web-worker and call it to get data back and fill form type="text"
thank you in advance.
Web workers don't have direct access to the DOM. So to do this, you'd need to gather the values of all 5-50k inputs into an array or similar, and then send that to the web worker (via postMessage) for processing, and have the web worker do the relevant processing and post the result back, and then use that result to update the inputs. See any web worker tutorial for the details of launching the worker and passing messages back and forth (and/or see my answer here).
Even just gathering up the values of the inputs and posting them to the web worker is going to take significant time on the main UI thread, though, as is accepting the result from the worker and updating the inputs; even 5k inputs is just far, far too many for a web page.
If maintaining browser responsiveness is the issue, then releasing the main thread periodically will allow the browser to process user input and DOM events. The key to this approach is to find ways to process the inputs in smaller batches. For example:
var INTERVAL = 10; // ms
var intervalId = setInterval((function () {
var values = [];
var $input = $('input[type=\'text\']');
var index;
return function () {
var $i = $input[index];
var el = $i.get();
$i.removeClass('double-error');
if (el.value != '') {
values[el.value] = 0;
$input.each(function() {
if (this.value == el.value) {
values[el.value]++;
}
});
}
if (index++ > $input.length) {
clearInterval(intervalId);
index = 0;
// Now set elements
intervalId = setInterval(function () {
var $i = $input[index];
var el = $i.get();
if (values[el.value] > 1) {
var name = el.value;
var product_model = $i.parent().parent().find('.product-model').text();
var m = product_model.toLowerCase().areplace(search,replace);
$i.parent().find('input[type=\'text\']').val(name + '-' + m);
}
if (index++ > $input.length) {
clearInterval(intervalId);
}
}, INTERVAL);
}
};
}()), INTERVAL);
Here, we do just a little bit of work, then use setInterval to release the main thread so that other work can be performed. After INTERVAL we will do some more work, until we finish and call clearInterval

Retry when no response from website

I use the recursive function below, in order to reopen website if httpstatus != 200:
retryOpen = function(){
this.thenOpen("http://www.mywebsite.com", function(response){
utils.dump(response.status);
var httpstatus = response.status;
if(httpstatus != 200){
this.echo("FAILED GET WEBSITE, RETRY");
this.then(retryOpen);
} else{
var thisnow = hello[variable];
this.evaluate(function(valueOptionSelect){
$('select#the_id').val(valueOptionSelect);
$('select#the_id').trigger('change');
},thisnow);
}
});
}
The problem is that sometimes the retryOpen function does not even go as far as to callback function(response){}. Then, my script freezes.
I wonder how one could change the function to be able to recursively try to open website again if there is no response from website (not even some error code as 404 or something)? In other words, how to rewrite the retryOpen function so it reruns when the function does not reach callback after a certain amount of time?
I would try something like this. Please note this is untested code, but should get you on the correct path
retryOpen = function(maxretry){
var count = 0;
function makeCall(url)
{
this.thenOpen(url, function(response){
utils.dump(response.status);
});
}
function openIt(){
makeCall.call(this,"http://www.mywebsite.com");
this.waitFor(function check() {
var res = this.status(false);
return res.currentHTTPStatus === 200;
}, function then() {
var thisnow = hello[variable];
this.evaluate(function(valueOptionSelect){
$('select#the_id').val(valueOptionSelect);
$('select#the_id').trigger('change');
},thisnow);
}, function timeout() { // step to execute if check has failed
if(count < maxretry)
{
openIt.call(this);
}
count++
},
1000 //wait 1 sec
);
}
openIt();
}

CouchDB _changes notifications - jquery.couch.js couch.app.db.changes() usage

I have replication working in CouchDB and want to update my UI when changes are pushed to the target database. I've read about _changes database API and found the couch.app.db.changes() function in jquery.couch.js However I can't work out how to use the function. I assume I need to set up listener, but my knowledge of Javascript is not yet what it needs to be.
Unfortunately the docs at http://www.couch.io/page/library-jquery-couch-js-database don't even list the changes() function.
Can someone help me here and also let me know what the options param is for.
Here is the code for the function in question:
changes: function(since, options) {
options = options || {};
// set up the promise object within a closure for this handler
var timeout = 100, db = this, active = true,
listeners = [],
promise = {
onChange : function(fun) {
listeners.push(fun);
},
stop : function() {
active = false;
}
};
// call each listener when there is a change
function triggerListeners(resp) {
$.each(listeners, function() {
this(resp);
});
};
// when there is a change, call any listeners, then check for another change
options.success = function(resp) {
timeout = 100;
if (active) {
since = resp.last_seq;
triggerListeners(resp);
getChangesSince();
};
};
options.error = function() {
if (active) {
setTimeout(getChangesSince, timeout);
timeout = timeout * 2;
}
};
// actually make the changes request
function getChangesSince() {
var opts = $.extend({heartbeat : 10 * 1000}, options, {
feed : "longpoll",
since : since
});
ajax(
{url: db.uri + "_changes"+encodeOptions(opts)},
options,
"Error connecting to "+db.uri+"/_changes."
);
}
// start the first request
if (since) {
getChangesSince();
} else {
db.info({
success : function(info) {
since = info.update_seq;
getChangesSince();
}
});
}
return promise;
},
Alternatively you can use longpoll changes feed. Here is one example:
function bind_db_changes(database, callback) {
$.getJSON("/" + database, function(db) {
$.getJSON("/"+ database +
"/_changes?since="+ db.update_seq +"&heartbeat=10000&feed=longpoll",
function(changes) {
if($.isFunction(callback)){
callback.call(this, changes);
bind_db_changes(database, callback);
}
});
});
};
bind_db_changes("test", function(changes){
$('ul').append("<li>"+ changes.last_seq +"</li>");
});
Note that $.couch.db.changes is now in the official documentation:
http://daleharvey.github.com/jquery.couch.js-docs/symbols/%24.couch.db.changes.html
Also a nice example of consuming _changes with the jquery.couch plugin here:
http://bradley-holt.com/2011/07/couchdb-jquery-plugin-reference
what about using the ajax-feateures of jquery?
function get_changes() {
$.getJSON("/path/to/_changes", function(changes) {
$.each(changes, function() {
$("<li>").html(this.text).prependTo(mychanges_div);
});
get_changes();
});
}
setTimeout(get_changes, 1000);
I've been doing work with JS Promises code which enabled mt to understand the CounchDB code I posted above. Here is a sample:
var promise_changes = app.db.changes();
// Add our deferred callback function. We can add as many of these as we want.
promise_changes.onChange( db_changes );
// called whenever this db changes.
function db_changes( resp ) {
console.log( "db_changes: ", resp );
}
Google Chrome goes into a Busy state with long polling, which I hope they will resolve one day.

Categories