[翻译]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);
}
 
相关文档:
玩PHP、Delphi、Java基本上都有对象,习惯这种思路后上手任何语言都想靠OO思路,这绝不是在赶时髦,而是把相关代码进行内聚的确可以体会到维护的方便!
在JavaScript中如何创建对象?
JavaScript是基于对象的!它也是以Object为根类,其它类继承之。在根类提供了几个方法。供继承类使用!
以下是创建对象的例子:
funct ......
AJAX (异步 JavaScript 和 XML) 是个新产生的术语,专为描述JavaScript的两项强大性能.这两项性
能在多年来一直被网络开发者所忽略,直到最近Gmail, Google suggest和google Maps的横空出世才使人
们开始意识到其重要性.
这两项被忽视的性能是:
* 无需重新装载整个页面便能向服务器发送请求.
* 对XML文档的解析和处理.
......
function total(){
var i=0;
for(j=1;j<=20;j++)
{
var step="step"+j;
if(document.getElementById(step)){
if(document.getElementById(step).checked==true)
{
i=i+parseInt(document.getElementById(step).value);
}
}
}
document.getElementById("total").innerHTML = i;
}
function Resetvalue(){
......
Conditionals 条件表达式
Similar in nature to loops, conditionals determine how execution flows through JavaScript. The traditional argument of whether to use if-else statements or a switch statement applies to JavaScript just as it does to other languages. Since different b ......