这是我的代码的简化和解释版本:
var ptext=parr.find('div.ptext'); //Text Container
var pt=ptext.html(); //Text Container's string
var pdv=[pt.split(" ")]; //Text Container's array of words
pdv.push(pdv[0].length); //Write also the number of words
var ht=hp.html(); //Text Container's new string
var hdv=[ht.split(" ")]; //Text Container's new array of words
hdv.push(hdv[0].length); //New number of words
var kakaka=0; //If they begin with the same,
for (var j=0;j<hdv[0].length;j++){ //Animate only from the position
if (hdv[0][j]==pdv[0][j]) //where they differ
kakaka+=2;
}
window.clearTimeout(ptext.data('curt')); //Clear current animation's interval
ptext.data('count',kakaka); //Set starting position
ptext.data('curt', //Set interval's var into object
window.setInterval((function (item,pdv,hdv,text_callback) {
return function() { //item = text obj, text_callback= callback function
var i=item.data('count');
i=(i==undefined)?0:1+i;
item.data('count',i); //increase counter
//first phase - remove old text
if (i<=pdv[1]) // go on
{
item.html((pdv[0].slice(0,pdv[1]-i)).join(' '));
} //if reached the position, add new text
else if (i<=pdv[1]+hdv[1])
{
item.html((hdv[0].slice(0,i-pdv[1])).join(' '));
} //if finish clear timeout and call callback
else {
item.data('count',0);
window.clearTimeout(item.data('curt'));
text_callback();
}
}
})(ptext,pdv,hdv,text_callback),8) //8 = supposed interval
);
}
它从 div 中获取单词,快速将它们一一删除,然后用新文本填充它。
它使用 .setInterval() 函数,该函数应该每 8 毫秒回调一次。这在我的 i5 CPU 上运行良好,但在 i3 笔记本电脑上却非常慢。
您能否就如何提高性能提供一些建议?