[·Òë]High Performance JavaScript(021)
Splitting Up Tasks ·Ö½âÈÎÎñ
What we typically think of as one task can often be broken down into a series of subtasks. If a single function is taking too long to execute, check to see whether it can be broken down into a series of smaller functions that complete in smaller amounts of time. This is often as simple as considering a single line of code as an atomic task, even though multiple lines of code typically can be grouped together into a single task. Some functions are already easily broken down based on the other functions they call. For example:
ÎÒÃÇͨ³£½«Ò»¸öÈÎÎñ·Ö½â³ÉһϵÁÐ×ÓÈÎÎñ¡£Èç¹ûÒ»¸öº¯ÊýÔËÐÐʱ¼äÌ«³¤£¬ÄÇô²é¿´ËüÊÇ·ñ¿ÉÒÔ·Ö½â³ÉһϵÁÐÄܹ»¶Ìʱ¼äÍê³ÉµÄ½ÏСµÄº¯Êý¡£¿É½«Ò»ÐдúÂë¼òµ¥µØ¿´×÷Ò»¸öÔ×ÓÈÎÎñ£¬¶àÐдúÂë×éºÏÔÚÒ»Æð¹¹³ÉÒ»¸ö¶ÀÁ¢ÈÎÎñ¡£Ä³Ð©º¯Êý¿É»ùÓÚº¯Êýµ÷ÓýøÐвð·Ö¡£ÀýÈ磺
function saveDocument(id){
//save the document
openDocument(id)
writeText(id);
closeDocument(id);
//update the UI to indicate success
updateUI(id);
}
If this function is taking too long, it can easily be split up into a series of smaller steps by breaking out the individual methods into separate timers. You can accomplish this by adding each function into an array and then using a pattern similar to the array-processing pattern from the previous section:
Èç¹ûº¯ÊýÔËÐÐʱ¼äÌ«³¤£¬Ëü¿ÉÒÔ²ð·Ö³ÉһϵÁиüСµÄ²½Ö裬°Ñ¶ÀÁ¢·½·¨·ÅÔÚ¶¨Ê±Æ÷Öе÷Óá£Äã¿ÉÒÔ½«Ã¿¸öº¯Êý¶¼·ÅÈëÒ»¸öÊý×飬ȻºóʹÓÃǰһ½ÚÖÐÌáµ½µÄÊý×é´¦Àíģʽ£º
function saveDocument(id){
var tasks = [openDocument, writeText, closeDocument, updateUI];
setTimeout(function(){
//execute the next task
var task = tasks.shift();
task(id);
//determine if there's more
if (tasks.length > 0){
setTimeout(arguments.callee, 25);
}
}, 25);
}
 
Ïà¹ØÎĵµ£º
JavaScriptʼþ´óÈ«
click() ¶ÔÏó.click() ʹ¶ÔÏó±»µã»÷¡£
closed ¶ÔÏó.closed ¶ÔÏó´°¿ÚÊÇ·ñÒѹرÕtrue/false
clearTimeout(¶ÔÏó) Çå³ýÒÑÉèÖõÄsetTimeout¶ÔÏó
clearInterval(¶ÔÏó) Çå³ýÒÑÉèÖõÄsetInterval¶ÔÏó
confirm("ÌáʾÐÅÏ¢") µ¯³öÈ·ÈÏ¿ò£¬È·¶¨·µ»ØtrueÈ¡Ïû·µ»Øfalse
cursor:Ñùʽ ¸ü¸ÄÊó±êÑùÊ ......
Òþ²Ø³ÉÔ±±äÁ¿
ÔÚº¯ÊýÌåÄÚ¶¨ÒåµÄ±äÁ¿Îª¾Ö²¿±äÁ¿£¬À뿪º¯Êý¾Í¹ÒµôÁË
ÔÚº¯ÊýÌåÄÚʹÓÃthis.³ÉÔ±±äÁ¿Ãû£¬ÔòΪwindow¶ÔÏó¼¶±äÁ¿£¬¼´È«¾Ö±äÁ¿
¹ÊÐèÒªÕâÑùÒþ²Ø³ÉÔ±±äÁ¿£¬ÏòÍâÖ»±©Â¶get¡¢setº¯Êý
function testClass(name){
var _firstname=name;
return {
getname : function() {
return _fir ......
Recursion Patterns µÝ¹éģʽ
When you run into a call stack size limit, your first step should be to identify any instances of recursion in the code. To that end, there are two recursive patterns to be aware of. The first is the straightforward recursive pattern represented ......
Yielding with Timers Óö¨Ê±Æ÷Èóöʱ¼äƬ
Despite your best efforts, there will be times when a JavaScript task cannot be completed in 100 milliseconds or less because of its complexity. In these cases, it's ideal to yield control of the UI thread so that UI updates may occur ......