In the example below, can anyone tell me how to make ‘slow response when clicked’ respond more quickly without modifying appendContent()? I’m wondering if there’s a way to place cheap operations before more expensive ones, and make sure the cheap ones actually get carried out quickly.
<div id='draw'>slow response when clicked</div> <div style='overflow: auto; height: 300px; border:solid 1px grey' id='content'></div> <script language='javascript'> var clickLink = document.getElementById('draw'); var contentDiv = document.getElementById('content') function appendContent(){ contentDiv.innerHTML = contentDiv.innerHTML + 'hello '; } clickLink.onclick = function(){ clickLink.style.color = 'red'; for (var i = 0; i < 1500; i++){ appendContent(); } }; </script>
The mechanism for feedback should be different for the duration the user has to wait. Less than 0.1 seconds and a user will not notice.
Between 1 and 10 seconds you can simply display a symbol such as an animated gif of some sort that indicates your app is processing. See http://www.ajaxload.info/ I use a div with an ID ‘processing’ and style it with a spinner and use the following jquery code to show and hide it before and after the process.
Beyond 10 seconds it would be ideal to provide an estimate of processing time.
See Response Time Overview for the source of these numbers.
The following code immediately changes the link colour to red and calls the append method a fraction of a second later. Essentially is allows the browser to execute a separate thread before getting hung up in a loop. The timeout may need to be adjusted depending on the browser. Check out Neil Mix’s Threading in JavaScript 1.7 if you need to relinquish control in a more generic manner.