Javascript中的setTimeout,setInterval,requestAnimFrame

         这三种方法我们平时初学的时候可能容易混淆,下面我们将使用例子的形式来阐述这三种方法不同的用法。

         setTimeout:Calls a function or executes a code snippet after a specified delay.(在特定的时间后执行方法和代码块)

       语法:var timeID = setTimeout(func|code,delay) 

	<script type="text/javascript">
		/*第一种写法
		function f(){
			console.log("HI");	
		}
		setTimeout(f,1000);
		*/

		/*第二种写法
		setTimeout("console.log('aaa')",2000);
		*/                                                                                                                                                        //第三种写法
		setTimeout(function(){console.log("bbb")},2000);
	</script>
             在2秒之后执行输出操作

          复杂一点例子:

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script type="text/javascript">
		/*
			延迟几秒后调用该方法
		*/
		var timeoutID;
		function delayedAlert(){
			timeoutID = window.setTimeout(slowAlert,2000);
		}
		function slowAlert(){
			console.log("That was really show~");
		}
		function clearAlert(){
			window.clearTimeout(timeoutID);
		}
	</script>
</head>
<body>
	<p>Live Example</p>
	<button οnclick="delayedAlert();">Show an alert box after two seconds</button><p></p>
	<button οnclick="clearAlert();">Cancel alert before it hanppeds</button>
</body>
</html>

       打开页面并打开浏览器控制台,点击"show an alert..." 按钮,就看到我们在2秒后在控制台输出"That was really show~~~"  点击一次2秒后就输出【可以点击多次哦~】 

          点击“Cancel alert before it happends” 按钮后,就能够取消正在执行的delayedAlert()方法【执行完打印输出后就没作用了~】


         让我们再来看setInterval()方法

         setInterval() : Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function. Returns an intervalID.(在时间间隔内永久重复的执行函数和代码块,返回一个intervalID),下面是一个颜色变幻的例子:

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script type="text/javascript">
	    /*
			和前面的setTimeout 挺相像的
			有一个nItervId,清除的时候就用clearInterval(id)方法清除就可以了~
	    */
		var nIntervId;
		function changeColor(){
			nIntervId = setInterval(flashText,500);
		}
		function flashText(){
			var oElem = document.getElementById("my_box");
			oElem.style.color = oElem.style.color == "red" ? "blue" : "red";
		}

		function stopTextColor(){
			clearInterval(nIntervId);	
		}
	</script>
</head>
<body οnlοad="changeColor();">
	<div id="my_box">
		<p>Hello World!</p>
	</div>
	<button οnclick="stopTextColor();">Stop</button>
</body>
</html>

        上述例子会在0.5秒后执行颜色变幻功能,并永久不断的执行下去。当然我们点击Stop按钮,就可以停止颜色变幻,这里的clearInterval(nIntervId) 是根据我们setInterval方法返回的ID来停止使用他们的。


         最后来说对我比较陌生的window.requestAnimFrame,这个方法给我们在绘制的过程中有一个平滑的过渡,这个方法的性能比setTimeout和setInterval要好点。所以接下来我们将介绍它怎么使用。

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>startGirl</title>
</head>
<body οnlοad="init()">
	<div>
		<canvas id="canvas" width="800px" height="600px"></canvas>
	</div>
	<script type="text/javascript">
		/*
			拿到我想要的canvas
		*/
		var can;
		/*
			绘制2D图形的context
		*/
		var ctx;
		/*
			定义宽高
		*/
		var w;
		var h;
		function init(){
			can = document.getElementById("canvas");
			ctx = can.getContext("2d");
			w = can.width;
			h = can.height;
			console.log("canvas w:"+w);
			console.log("canvas h:"+h);
			drawLoop();

		}
		function drawLoop(){
			window.requestAnimFrame(gameLoop);
			fillCanvas();
	
		}
		function fillCanvas(){
			ctx.fillStyle = "#393550";
			ctx.fillRect(0,0,w,h);
		}                                                                                                                                                         //浏览器的兼容设置
		window.requestAnimFrame = (function() {
			return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
				function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
					return window.setTimeout(callback, 1000 / 60);
				};
		})();
	</script>
</body>
</html>

        我们可以在这个网站看到setTimeout和requestAnimFrame性能参数的比较。http://ie.microsoft.com/testdrive/graphics/RequestAnimationFrame/Default.html#  

        tips :在我们实际项目绘画的过程中,不推荐使用多个setInterval()或setTimeout()一起使用,他们会占用CPU性能。

       转载请注明出处:Coder的不平凡 http://blog.csdn.net/pearyangyang/article/details/45561115

     

      

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值