教你用JavaScript制作定时器
1、首先新建一个index文件<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> </head> <body> </body></html>
2、在head里写写个script标签<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript"> </script> </head> <body> </body></html>
3、在body里写一个按钮<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript"> </script> </head> <body> <div id="id"></div> <button id="btn">关闭</button> </body></html>
4、在script标签里写<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript"> window.onload = function(){ } </script> </head> <body> <div id="id"></div> <button id="btn">关闭</button> </body></html>让它先加载网页再加载js模块
5、获取body里div的id<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript"> window.onload = function(){ var time = document.getElementById("id"); } </script> </head> <body> <div id="id"></div> <button id="btn">关闭</button> </body></html>
6、声明一个变量<!DOCTYP苇质缵爨E html><html> <head> <meta charset租涫疼迟="UTF-8"> <title></title> <script type="text/javascript"> window.onload = function(){ var time = document.getElementById("id"); var i = 0; } </script> </head> <body> <div id="id"></div> <button id="btn">关闭</button> </body></html>
7、在这里写一个定时器<!DOCTYPE html><html>挢旗扦渌; <head> <稆糨孝汶;meta charset="UTF-8"> <title></title> <script type="text/javascript"> window.onload = function(){ var time = document.getElementById("id"); var i = 0; time = setInterval(function(){ id.innerHTML = i++;//写一个定时器,第一个参数函数中获取变量i的值 },1000);//第二个参数是它每次变动所间隔的时间,单位量为毫秒1000毫秒等于1秒 </script> </head> <body> <div id="id"></div> <button id="btn">关闭</button> </body></html>
8、再写一个定时器关闭的函数<!DOCTYPE html><html> 争犸禀淫<head> <meta charset="UTF-8"> <title></title> <script type="text/javascript"> window.onload = function(){ var time = document.getElementById("id"); var i = 0; time = setInterval(function(){ id.innerHTML = i++;//写一个定时器,第一个参数函数中获取变量i的值 },1000);//第二个参数是它每次变动所间隔的时间,单位量为毫秒1000毫秒等于1秒 var button = document.getElementById("btn");//获取按钮id button.onclick = function(){ clearTimeout(time);//点击按钮关闭定时器 } } </script> </head> <body> <div id="id"></div> <button id="btn">关闭</button> </body></html>
9、最后快捷键Ctrl+R网页运行~~~一个定时器就出来啦~