关于JavaScript性能的一些总结

一:用定时器代替for循环


for循环append()内容到dom中,是要等循环结束后才会在dom 中显示出来,如果改用定时器,就会一条一条的显示在页面中。
而且循环次数多的时候,for循环相对于定时器的做法卡。

for
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>菜鸟教程(runoob.com)</title> 
<script src="https://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
for(var index= 0 ; index <100 ; index++ ){
	$("body").append(index)
}
});
</script>
</head>
<body>
<p>如果你点我,我就会消失。</p>
<p>继续点我!</p>
<p>接着点我!</p>
</body>
</html>





定时器
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title></title> 
<script src="https://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
				var index = 0;
				var times = window.setInterval(function(){
				$("body").append(index);
					index++;
					if(index==1000){
						clearInterval(times);
					}
				}, 0);
});
</script>
</head>
<body>
</body>
</html>







猜你喜欢

转载自blog.csdn.net/qianqianyixiao1/article/details/53884499