Javascript method works and doesn't work - javascript

I'm having a hard time even asking this question because I don't understand what is going on.
Basically, I have a spinning loader element that should be displayed while my javascript runs. At the end of the javascript the loader should be turned off and a modal should be displayed with data queried from a database. The problem is that the loader is never displayed. Theres about a 1 - 2 second wait while the queries run before the modal is created.
function includeConnectionJS() {
if (!(typeof sforce === "object")) {
var connectionJS = document.createElement('script');
var documentHead = document.getElementsByTagName('head')[0];
connectionJS.src = '/soap/ajax/38.0/connection.js';
connectionJS.setAttribute('onload', 'createLoader();createModal();');
documentHead.appendChild(connectionJS);
} else {
createLoader();
// Checks to see if the loader element exists. If it does not, create the element and than toggle it to display it.
// If the element already exists, display the modal
createModal();
// Checks to see if the modal element exists, if it does not, create the element and than turn off the loader and display the modal.
// If the element already exists, turn off the loader and display the modal
}
}
I put console.logs in my methods and I can clearly see that the method is being called, the if statements are all passing and the visibility of the element is changing to the correct values at the correct times. Everything seems to imply that it should be working, but the element is never actually displayed.
I was able to get it to display by changing the call to createModal to look like the following:
setTimeout(function(){createModal()}, 100); // Most values for delay worked.
I don't want to create an artificial delay just to show loader for effect.
My primary concern is that the createModal method makes calls to the database. These cause delays in the javascript execution (I call them synchronously, not asynchronously). I can clearly see the loader display being set to 'block' before the queries, watch all the queries call out and return and see the display of the loader change back to 'none' all in the correct order. More than that, if I call the createLoader(); method directly from the console, it works.
I just can't figure out what it is I'm missing.

With synchronous Javascript calls you are blocking the UI and other functions queued in the Event Loop https://developer.mozilla.org/en/docs/Web/JavaScript/EventLoop#Run-to-completion. It's important to remember that Javascript code executes in a single-thread. So no code can execute in parallel, everything else has to wait until the current task is done. In practice this means that you want your functions to do their job as quickly as possible so that other operations (UI updates, keyboard/mouse events etc., timeouts, or asynchronous callbacks etc.) can execute. They all have to wait until you pass back control to the engine through completing the current code block.
setTimeout works because it adds the long running createModal function to the Event Queue for execution sometime in the future (even when set to 0ms - it doesn't guarantee immediate execution it just says at first opportunity you can sometime after 0ms has elapsed. If you have a long running function that might actually be 10s later). Doing this allows the calling function to complete quickly and the UI is now able to apply any updates. Now when the javascript engine is ready to run further code it will look for the next block of code recorded in the Event Loop. This time when it runs createModal it will again block updates to the UI etc., handing mouse & keyboard events etc., but now the UI has had the opportunity to update, you'll have your spinner up.
So the choices are: either use asynchronous calls in your function so that it completes quickly, or if that's not possible continue using setTimeout() to queue the long running task after the UI has updated.

Related

Triggering course completion in SCORM 1.2

I've got SCORM 1.2 saving and updating objectives correctly but I can't seem to trigger the actual course completion. When the course is loaded into our test Managed Learning Environment (MLE) we get the following behaviour:
When the last objective is completed, the course completion fires off, as expected.
The SCORM console.log-ing says the course completion has been recorded successfully.
When the user closes the course window, the course completion is in fact NOT registered with our MLE.
When the user returns to the course and completes any objective (which have all previously been completed) the course completion fires off again, as expected - but this time when they close the course window, the course completion HAS registered with our MLE.
So, is there something about the exit characteristics that I should be including?
Here's how we set up an objective:
vault.SCORM.set('cmi.objectives.'+numberOfObjectives+'.id', tempComponentString);
vault.SCORM.save();
vault.SCORM.set('cmi.objectives.'+numberOfObjectives+'.status', 'incomplete');
vault.SCORM.save();
Here's how the objectives get completed:
vault.SCORM.set("cmi.objectives." + pages[pageId-1].componentSCORMIndexesById[element.componentId()] + ".status" , "completed");
vault.SCORM.save();
Those are all working fine. It's the course completion that's the problem. Here's the code for that:
vault.SCORM.set("cmi.core.lesson_status" , "completed");
vault.SCORM.save();
Just to repeat: This course completion console.logs as if it has fired off correctly the first time the course is actually completed, but the course is only registered as complete with our MLE when the user returns to the course and clicks a completed component (which triggers an objective completion and the above course completion again).
Is there something about how we've set up the objectives that would be preventing actual completion the first time? Or is it to do with exit characteristics / suspend data?
If anyone has any pointers, that would be great!
EDIT
I've done some more testing and temporarily taken OUT the calls to set 'cmi.objectives'. The course completion now works correctly. So it's something about the presence of the objectives that's preventing the course completing correctly. Is there some extra property that needs to be set to really complete an objective?

Javascript: Atomicity / Interactions between browser view and DOM

I have two specific Javascript questions that are probably answered by one general answer. Please feel free to also submit the corresponding general question--I have difficulties expressing myself.
When I manipulate multiple DOM elements in a single Javascript callback, is the view possibly updated "live" with each individual manipulation, or atomically after the callback returns?
When a user clicks an HTML element twice in a short timeframe, and the corresponding click handler disables the HTML element, is there a guarantee that the handler won't be executed twice?
Preemptively, I do not have a standards citation for this. This is strictly in my experience.
I have never noticed the visible pixels update while Javascript is executing in real time. I suspect that they will not during the standard operation of the browser - it certainly is possible that debugging presents an exception. I have, however, observed synchronous reflow calculations occurring on DOM elements between the top and bottom of a single function call, but these reflow calculations never made it to the pixel buffer ( that I noticed ). These appear to occur synchronously.
function foo() {
$('#myElement').width(); // 100
$('#myElement').parent().width(); // 150
$('#myElement').css('width', 200);
$('#myElement').width(); // 200
$('#myElement').parent().width(); // 250
}
Regarding multiple clicks on an element that is disabled within the click handler, I suspect that the second click will not fire. I believe when the operating system receives a click event it passes it to the browser and it is placed in a queue. This queue is serviced by the same thread that executes Javascript. The OS click event will remain in the queue until Javascript completes execution at which time it will be removed, wrapped as a browser click event, and bubbled through the DOM. At this point the button will already be disabled and the click event will not activate it.
I'm guessing the pixel buffer is painted on-screen as another operation of this same thread though I may be mistaken.
This is based on my vague recollection of standards that I have seen quoted and referenced elsewhere. I don't have any links.
All script executions happen within the same thread. Therefore you can never have simultaneous actions and don't have to worry about concurrent modification of elements. This also means you don't need to worry about a click handler being fired while one is currently executed. However, this doesn't mean they cant immediately fire it again when your script is finished. The execution may be so fast that its indistinguishable.
First Bullet: The updates will be live. For example, attach the following function to an onclick handler:
function(){
var d = document.getElementById("myelement")
d.setAttribute("align", "center")
d.setAttribute("data-foo","bar")
d.setAttribute("data-bar","baz")
}
Now load this in your browser set a breakpoint on the first line. trigger the event and step through line-by-line while watching the DOM. The updates will happen live, they are not going to happen all at once.
If you want them to happen atomically, you'll want to clone the DOM element in question, make the changes on the clone, then replace the original element with the clone. The cloned element is still being updated in realtime, but the user-visible effect is atomic.
Second Bullet: If the second click event comes in after the element has been disabled, then yes, you won't get a second callback. But if there is any delay between the first click and the disable call, (for example some kind of lengthy check needs to be performed to determine if the element should be disabled) and the second click occurs in that delay, it will fire the callback a second time. The browser has no way to know that multiple click events isn't acceptable behavior in a given script.

jQuery - how to call ajax when certain condition is met

I know you can use the function setInterval to call your ajax function at fixed time interval. What I'd like to achieve though is something like this:
while (true) //but obviously this while loop will block other code. I'd like it non-blocking
{ //if certain condition is met, call my ajax function.
}
so basically the code should sit silently in the background, listening. if certain condition is meet, fire ajax call.
Is is possible in jquery/javascript?
Edit: For conditions: basically, I will be automatically scrolling the rows of a large table (that is another question, another post...), once it reaches the last row, the condition is met, ajax is called to fetch data from the server, re-populate the table, and start automatically scrolling again.
In Javascript, conditions do not "become met" all by themselves.
It's (mostly) a single threaded language, where the UI thread just sits around waiting for events to happen, and in response the programmer supplied event handlers go do stuff. So long as they're doing stuff, the UI thread is unable to handle any more events.
This is why you shouldn't ever use a busy loop, or otherwise tie up the CPU doing long-winded calculations in a tight loop.
In summary, you shouldn't ever need to poll a condition - it should be evident when that condition becomes true because some event will have fired, allowing it to become true.
You should then be able to fire off your AJAX request in that event's handler.
EDIT you've now clarified that you want to do this when the scroll reaches the end of a table.
Per above, there is (of course) an event that tells you that something scrolled, and it'll tell you how far.
Look at http://api.jquery.com/scroll/
You need to register a handler for that event, and then trigger your AJAX call in that handler.
Certainly possible if you have an event. Then you can attach a handler to it.
So the question is: what condition ?

DOM input events vs. setTimeout/setInterval order

I have a block of JavaScript code running on my page; let's call it func1. It takes several milliseconds to run. While that code is running, the user may click, move the mouse, enter some keyboard input, etc. I have another block of code, func2, that I want to run after all of those queued-up input events have resolved. That is, I want to ensure the order:
func1
All handlers bound to input events that occurred while func1 was running
func2
My question is: Is calling setTimeout func2, 0 at the end of func1 sufficient to guarantee this ordering, across all modern browsers? What if that line came at the beginning of func1—what order should I expect in that case?
Please back up your answers with either references to the relevant specs, or test cases.
Update: It turns out that no, it's not sufficient. What I failed to realize in my original question was that input events aren't even added to the queue until the current code block has been executed. So if I write
// time-consuming loop...
setTimeout func2, 0
then only after that setTimeout is run will any input events (clicks, etc.) that occurred during the time-consuming loop be queued. (To test this, note that if you remove, say, an onclick callback immediately after the time-consuming loop, then clicks that happened during the loop won't trigger that callback.) So func2 is queued first and takes precedence.
Setting a timeout of 1 seemed to work around the issue in Chrome and Safari, but in Firefox, I saw input events resolving after timeouts as high as 80 (!). So a purely time-based approach clearly isn't going to do what I want.
Nor is it sufficient to simply wrap one setTimeout ... 0 inside of another. (I'd hoped that the first timeout would fire after the input events queued, and the second would fire after they resolved. No such luck.) Nor did adding a third, or a fourth, level of nesting suffice (see Update 2 below).
So if anyone has a way of achieving what I described (other than setting a timeout of 90+ milliseconds), I'd be very grateful. Or is this simply impossible with the current JavaScript event model?
Here's my latest JSFiddle testbed: http://jsfiddle.net/EJNSu/7/
Update 2: A partial workaround is to nest func2 inside of two timeouts, removing all input event handlers in the first timeout. However, this has the unfortunate side effect of causing some—or even all—input events that occurred during func1 to fail to resolve. (Head to http://jsfiddle.net/EJNSu/10/ and try rapidly clicking the link several times to observe this behavior. How many clicks does the alert tell you that you had?) So this, again, surprises me; I wouldn't think that calling setTimeout func2, 0, where func2 sets onclick to null, could prevent that callback from being run in response to a click that happened a full second ago. I want to ensure that all input events fire, but that my function fires after them.
Update 3: I posted my answer below after playing with this testbed, which is illuminating: http://jsfiddle.net/TrevorBurnham/uJxQB/
Move the mouse over the box (triggering a 1-second blocking loop), then click multiple times. After the loop, all the clicks you performed play out: The top box's click handler flips it under the other box, which then receives the next click, and so on. The timeout triggered in the mouseenter callback does not consistently occur after the click events, and the time it takes for the click events to occur varies wildly across browsers even on the same hardware and OS. (Another odd thing this experiment turned up: I sometimes get multiple jQuery mouseenter events even when I move the mouse steadily into the box. Not sure what's going on there.)
I think you are on the wrong track with your experiments. One problem is of course that you are fighting different message loop implementations here. The other (the one you didn't recognize it seems) is different double click handling. If you click the link twice you won't get two click events in MSIE - it's rather one click event and a dblclick event (for you that looks like the second click was "swallowed"). All other browsers seem to generate two click events and a dblclick event in this scenario. So you need to handle dblclick events as well.
As message loops go, Firefox should be easiest to handle. From all I know, Firefox adds messages to the queue even when JavaScript code is running. So a simple setTimeout(..., 0) is sufficient to run code after the messages are processed. You should refrain from hiding the link after func1() is done however - at this point clicks aren't processed yet and they won't trigger event handlers on a hidden element. Note that even a zero timeout doesn't get added to the queue immediately, current Firefox versions have 4 milliseconds as the lowest possible timeout value.
MSIE is similar, only that there you need to handle dblclick events as I mentioned before. Opera seems to work like that as well but it doesn't like it if you don't call event.preventDefault() (or return false from the event handler which is essentially the same thing).
Chrome however seems to add the timeout to the queue first and only add incoming messages after that. Nesting two timeouts (with zero timeout value) seems to do the job here.
The only browser where I cannot make things work reliably is Safari (version 4.0 on Windows). The scheduling of messages seems random there, looks like timers there execute on a different thread and can push messages into the message queue at random times. In the end you probably have to accept that your code might not get interrupted on the first occasion and the user might have to wait a second longer.
Here is my adaptation of your code: http://jsfiddle.net/KBFqn/7/
If I'm understanding your question correctly, you have a long-running function but you don't want to block the UI while it is running? After the long-running function is done you then want to run another function?
If so instead of using timeouts or intervals you might want to use Web Workers instead. All modern browsers including IE9 should support Web Workers.
I threw together an example page (couldn't put it on jsfiddle since Web Workers rely on an external .js file that has to be hosted on the same origin).
If you click A, B, C or D a message will be logged on the right. When you press start a Web Worker starts processing for 3 seconds. Any clicks during those 3 seconds will be immediately logged.
The important parts of the code are here:
func1.js The code that runs inside the Web Worker
onmessage = function (e) {
var result,
data = e.data, // get the data passed in when this worker was called
// data now contains the JS literal {theData: 'to be processed by func1'}
startTime;
// wait for a second
startTime = (new Date).getTime();
while ((new Date).getTime() - startTime < 1000) {
continue;
}
result = 42;
// return our result
postMessage(result);
}
The code that invokes the Web Worker:
var worker = new Worker("func1.js");
// this is the callback which will fire when "func1.js" is done executing
worker.onmessage = function(event) {
log('Func1 finished');
func2();
};
worker.onerror = function(error) {
throw error;
};
// send some data to be processed
log('Firing Func1');
worker.postMessage({theData: 'to be processed by func1'});
At this point, I'm prepared to say that, regrettably, there is no solution to this problem that will work under all browsers, in every scenario, every time. In a nutshell: If you run a JavaScript function, there's no way to reliably distinguish between input events that the user triggered during that time and those the user triggered afterward. This has interesting implications for JS developers, especially those working with interactive canvases.
My mental model of how JS input events work was off the mark. I'd thought that it went
The user clicks a DOM element while code is running
If that element has a click event handler, the callback is queued
When all blocking code has executed, the callback is run
However, my experiments, and those contributed by Wladimir Palant (thanks, Wladimir) show that the correct model is
The user clicks a DOM element while code is running
The browser captures the coordinates, etc. of the click
Some time after all blocking code has executed, the browser checks which DOM element is at those coordinates, then runs the callback (if any)
I say "some time after" because different browsers seem to have very different behaviors for this—in Chrome for Mac, I can set a setTimeout func2, 0 at the end of my blocking code and expect func2 to run after the click callbacks (which run only 1-3ms after the blocking code finished); but in Firefox, the timeout always resolves first, and the click callbacks typically happen ~40ms after the blocking code finished executing. This behavior is apparently beyond the purview of any JS or DOM spec. As John Resig put it in his classic How JavaScript Timers Work:
When an asynchronous event occurs (like a mouse click, a timer firing, or an XMLHttpRequest completing) it gets queued up to be executed later (how this queueing actually occurs surely varies from browser-to-browser, so consider this to be a simplification).
(Emphasis mine.)
So what does this mean from a practical standpoint? This is a non-issue as the execution time of blocking code approaches 0. Which means that this problem is yet another reason to hew to that old advice: Break up your JS operations into small chunks to avoid blocking the thread.
Web workers, as Useless Code suggested, are even better when you can use them—but be aware that you're foregoing compatibility with Internet Explorer and all major mobile browsers.
Finally, I hope browser-makers will move forward on standardizing input events in the future. This is one of many quirks in that area. I hope Chrome will lead the way to the future: excellent thread isolation, low event latency, and relatively consistent queueing behavior. A web developer can dream, can't he?
You can use dispatchEvent with a custom event name at the end of your function. This won't work on IE, but is still possible; just use fireEvent instead.
Take a look at this:
http://jsfiddle.net/minitech/NsY9V/
Click "start the long run", and click on the textbox and type in it. Voilà!
You can make the event handlers check to see if a flag is set by func1; if so queue func2 if not already queued.
This may either be elegant or ugly depending on the specializedness of func2. (Actually it's probably just ugly.) If you choose this approach, you need some way to hook events, or alternatively your own bindEvent(event,handler,...) function which wraps the handler and binds the wrapped handler.
The correctness of this approach depends on all the events during func1 being queued at the same time. If this is not the case, you can either make func2 idempotent, or (depending on the semantics of func2) put an ugly "cannot be called again for N milliseconds" lock on it.
please describe better you scenario.
What you need do
some time ago i need do something how that was so i build an simple javascript's routine across serialize async call in one sync call. maybe you could used that added one variant
for example that let me show how that work
first register all async or sync routines
second register end callback
third register call's to routines with yours parameters
fourth thrown process
in your case it neccesary added one call routine and that routine should be UoW of user actions.
Now the main problem is not call to routine in and order of execution if not track changes done by the user
first register all async or sync routines
second register end callback
third register call's to routines with yours paramter
--register your first routine
--register BlockUi //maybe for not accept more changes in the view
--register UiWriter // UoW of change done by user
--register you last routine
fourth thrown process
in real code that is one call dummy's function
function Should_Can_Serializer_calls()
{
RegisterMethods(model);
model.Queue.BeginUnitProcess(); //clear stack of execution, y others
model.Queue.AddEndMethod(SucessfullEnd); // callback to end routine
model.AbstractCall("func1",1,"edu",15,""); //set routine how first to execute
model.AbstractCall("BlockUi"); //track changes and user's actions
model.AbstractCall("UiWork"); //track changes and user's actions
model.AbstractCall("func2","VALUE"); //set second routine for execute
model.Process(); //throw call
}
Now the methods should be async for themselves for this you could use that library http://devedge-temp.mozilla.org/toolbox/examples/2003/CCallWrapper/index_en.html
so, what do you want do?

How to do something after my set of functions has been executed?

I have a set of functions, and I want to do something, like show a loading animation, while these functions are running! and when they stop i want to show an alert, for example.
All this on jQuery.
Anyone has a tip?
Some abstract code:
//these are my functions:
function a(number){number=number*2};
a(1); a(2); a(3);
//While this functions are running i want to show a gif, for example!
//When the three callings this function has done, i want to show an alert
Your JavaScript is executed in the same single thread as all other rendering within the document and it is therefore pointless to make a UI change before running a lot of synchronous JS (your functions) only to then reverse the UI change. The UI will remain the same to the user.
Doing what you want would only be useful in situations where asynchronous requests are occurring, and in such situations you would have to rely on callback functions.
Like this:
// code to show loading message
function a(number){number=number*2};
a(1); a(2); a(3);
// code to hide loading message
The code is executed from top to bottom, so by the time function are running, the loading message will be showing because it is before those functions and when functions are done, it will hide again.
just before the call to the function display some animation gif on the screen
and just after the call the function remove it and show your alert.
thats it.

Categories

Resources