实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>定时器</title> </head> <body> <button>登录</button> <button>取消</button> <p></p> <hr> <button>播放</button> <button>停止</button> <hr> <div style="width: 400px; height: 300px; background-color:lemonchiffon ;">我不是广告</div> <p id="res"></p> <script> var btn1=document.getElementsByTagName('button').item(0); var btn2=document.getElementsByTagName('button').item(1); var tips=document.getElementsByTagName('p').item(0); var timer =null; btn1.addEventListener('click',login,false); function login() { tips.innerText='正中跳转中...'; timer=setTimeout(function () { location.assign('http://www.baibu.com'); },3000); console.log(timer); } btn2.addEventListener('click',function (ev) { clearTimeout(timer); tips.innerText=null; console.log(timer); }); setInterval(function(){...}num) var btn3=document.getElementsByTagName('button').item(2); var btn4=document.getElementsByTagName('button').item(3); var img=document.images.item(0) btn3.addEventListener('click',play,false); function play() { timer= setInterval(function () { var index=Math.ceil(Math.random()*3); img.src='images/banner'+index+'.jpg'; console.log(img.src); },1000); } btn4.addEventListener('click',function (ev) { clearInterval(timer); },false); var div=document.getElementsByTagName('div').item(0); var res=document.getElementById('res'); var num=0;//点击 次数 var price=0.5; //事件模拟 var click=new Event('click'); setInterval(function () { div .dispatchEvent(click); num+=1; console.log(num); //输出收入情况 res.innerHTML='广告收入:'+'<span style="color: red">'+(num * price)+'</span>'+'元'; },2000); </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例