[SalesForce] Executing javascript asynchronously while waiting for result of action function

I have an <apex:actionFunction> which can take a long while to complete. While the action function is executing, I would like to be able to execute some on page JavaScript to make the users waiting experience more interesting (Changing onscreen messages etc)

  1. Call action function.
  2. Run on page JavaScript.
  3. When action function completes, stop on page JavaScript and run oncomplete code.

However, it seems that JavaScript is single threaded. Is there any way round this?

Thanks

Best Answer

A single event function is single-threaded in nature, and JavaScript itself generally behaves as if it were single-threaded (but WebWorkers provide multiple threads, and event handlers can execute in apparently multiple threads, as per a discussion on SE).

The best way to ensure a concurrent effect is to use setTimeout or setInterval on the animation function, thus allowing the browser to execute the animation periodically while processing occurs.

A demonstration of this animation procedure follows:

<script>
    var timerId = null;
    function doAnimationFrame() {
        // animation code here
    }
    function startAnimation() {
        timerId = setInterval(doAnimationFrame, 50); // 50ms is ~20 frames/second
    }
    function stopAnimation() {
        clearInterval(timerId);
    }
</script>
<!-- ... -->
<apex:actionFunction name="controllerFunction" action="{!controllerFunction}" reRender="form" oncomplete="stopAnimation()"/>
<apex:commandButton onclick="startAnimation(); controllerFunction(); return false;" value="Do Something!" />
Related Topic