Reputation: 1873
The other day, I wrote this function in JavaScript as a simple DTO for an object from a jQuery plugin. I assumed that if I wrote a general return gridColumns
line at the end of the function, the array could possibly be returned before my for
loop was finished populating it. So I wrote this while (true)
statement at the end, thinking I was being clever.
function getGridColumns() {
var gridColumns = [];
var records = $("#jqxGrid").jqxGrid("columns").records;
for (var i = 0; i < (records.length); i++) {
var obj = {
datafield: records[i].datafield,
width: records[i].width,
cellsalign: records[i].cellsalign,
hidden: records[i].hidden
}
gridColumns.push(obj);
}
while (true) {
if (gridColumns.length == records.length {
return gridColumns;
}
}
};
A buddy of mine looked at my little "hack" and said it was completely unnecessary, and I did some testing and determined that he's right.
So, here's where I'm at. How is JavaScript asynchronous, and how is it not? Can anyone help me understand this paradigm so that I can write better JavaScript?
Upvotes: 1
Views: 625
Reputation: 5962
The most common mechanisms that spawn new "threads" of execution and thus so to speak introduce an asynchronous situation in javascript are AJAX call callbacks (unless the call was specifically made synchrounous) and setInterval()
and setTimeout()
calls. As pointed out by Pointy, there are more than this though.
Upvotes: 2