I need to create a callback for a line of code that performs asynchronous work so that another a line of code can be called after it is finished. I’ve found a number of webpages that attempt to show how this can be done with two functions, one calling the other in Russian-doll fashion, but I can’t see how to do it with my code.
Below is my code. It takes the URL of a sound file, redefines a previously defined embed to point at that sound file, and then plays it. The problem is that I lose focus on the documentElement that was selected before the playIt() function is called. So in the playIt() function I save the focused element in a variable and focus() it after the embed-switcheroo and autoplay is performed. This doesn’t work, because the “e.parentNode.replaceChild(clone, e);” is performed asynchronously; when it finishes, it clears the focus in the document (internal id’s have changed? Reason unknown.) So I need the focus() code to follow the replaceChild() code. I want to accomplish this by having the focus() code execute as a callback following the replaceChild() code. How would I break this into two procedures, one calling the other, reproducing a synchronous flow?
[CODE]function playIt(soundFile){
//capture the element that’s currently focused:
focusedElement = document.activeElement;
// Set other variables:
var e = document.getElementById(“embedid”);
var clone = e.cloneNode(true);
clone.setAttribute(“src”, soundFile);
// *This* is the procedure that requires a synchronous callback
// Notice that there are two variables in use: e & clone:
e.parentNode.replaceChild(clone, e);
// This is what I want to run AFTER the
// “e.parentNode.replaceChild(clone, e);” line above
// Notice that it uses one variable: focusedElement:
if (focusedElement != null) {focusedElement.focus();}
// This line conceivably could directly come after the
// “e.parentNode.replaceChild(clone, e);” line above,
// but then the “focusedElemend.focus()” line must follow this line:
document.getElementById(’embedid’).autostart=’true’;
}
Many thanks,
~~Tom