JavaScript定时器函数

版权声明:原创文章,未经允许不得转载!!! https://blog.csdn.net/halo1416/article/details/82533970

1. 定时器函数的基本使用

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<!--
		1.如何定时?
		setTimeout(fn,ms)	在指定的毫秒数后调用函数或计算表达式,函数返回一个定时器的timeId。
		fn: 自定义函数
		ms: 函数的间隔调用周期,单位:毫秒
		
        setInterval(fn,ms)	按照指定的周期(以毫秒计)来调用函数或计算表达式,函数返回一个定时器的timeId。
        
        setTimeout调用一次
        setInterval调用多次(以周期为单位重复调用)
        
        2.如何取消定时?
        clearTimeout(timeId)	取消由 setTimeout() 方法设置的 timeId。
        clearInterval(timeId)	取消由 setInterval() 设置的 timeId。
        
        3.定时器函数的应用场景:一般用于制作动画效果,比如:轮播动画,倒计时跳转页面。
        -->
        <script type="text/javascript">
        	//设置定时器
        	var dsj1=setInterval(function() {
        		console.log("开始定时");
        		document.write("开始定时"+"<br/>");
        	},1000);
        	
        	
        	var dsj2=setTimeout(function() {
        		document.write("<b>5秒后显示此信息!</b><br/>");
        	},5000);
        	
        	//清除定时器
          	clearInterval(dsj1);
        	
        	
        	//网页的内容是访问者看的(就不能无限制的死循环),控制的内容是给开发人员看到(看到统计的次数)。
        	function dingshi() {
        		//document.write("开始定时100"+"<br/>");
        		console.log("开始定时100");
        	}
        	
        	//一定不要加()
        	//dingshi(); //运行一次函数
        	setInterval(dingshi,100);
        </script>
	</body>
</html>

2. 定时跳转实例

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			#d2 span
			{
				color: red;
				font-family: verdana;
				font-size:18;
				font-weight: bold;
			}
		</style>
	</head>
	<body>
		<div id="d1">
			<p>用户账号:<input type="text" id="yhm" /></p>
			<p>登录密码:<input type="password" id="pwd" /></p>
			<p><input type="button" value="登 录" onclick="check();" /></p>
		</div>
		<div id="d2" style="display: none;">
			登录成功! 系统将在 <span id="djsNum">5</span> 秒后跳转到会员中心!
	    </div>
		<script type="text/javascript">
			//制作一个倒计时5秒钟的页面,时间显示为0时跳转到淘宝首页
			function check() {
				//1. 先验证登录
				var yhm=document.getElementById("yhm").value;
				var pwd=document.getElementById("pwd").value;
				//从数据库中取出账号和密码进行验证,密码一般是使用md5的32位加密
				if(yhm=="张三" && pwd=="123456")
				{
					//2. 验证通过做倒计时页面
					document.getElementById("d1").style.display="none";
					document.getElementById("d2").style.display="block";
					
					//找到计时的数字,每隔1秒钟-1
					var timeID=setInterval(function() {
						//获取
						var num=parseInt(document.getElementById("djsNum").innerText);
						
						//数字为0时就清除定时器
						if(num==0)
						{
							clearInterval(timeID);
							location.href="http://www.baidu.com";
						}
						else
						{
							//设置
						    document.getElementById("djsNum").innerText=num-1;
						}
					},1000);
				    
				    //3. 倒计时结束时跳转到会员中心
				}
				else
				{
					alert("账号和密码错误!");
				}
			}
		</script>
	</body>
</html>

文章仅为本人学习过程的一个记录,仅供参考,如有问题,欢迎指出

猜你喜欢

转载自blog.csdn.net/halo1416/article/details/82533970
今日推荐