几个例子弄懂JS 的setInterval的运行方式
这篇文章主要介绍了js的setInterval方法的用法以及示例,非常的有用,这里推荐给小伙伴们。
setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的参数。
setinterval()用法
setInterval(code,millisec[,"lang"])
后面就两个参数code是你的js代码,millisec为时间间隔,以毫秒计
案例一:滚动条的控制
<script type="text/javascript"> var t = setInterval(function(){ window.scrollBy(0,20); console.log(document.body.scrollTop); if(document.body.scrollTop || document.documentElement.scrollTop >= 100){ clearInterval(t); } }, 1000); </script>
案例二:页面显示时间
<html> <head> <meta charset="UTF-8"> <title>setInterval案例</title> </head> <body style="height: 2000px"> <input type="text" name="clock" id="clock" value="" style="width: 500px;"/> <button id="stop" onclick="timer=window.clearInterval(timer)">停止时间函数</button> <script type="text/javascript"> function clock(){ var t = new Date(); document.getElementById('clock').value = t; } var timer = setInterval(clock, 50); var stop = document.getElementById('stop'); stop.onclick = function(){ clearInterval(timer); } </script> </body> </html>
案例三:
function show(){ console.log("每隔一秒我就会显示一次"); } var sh; sh=setInterval(show,1000); clearInterval(sh);
案例四:类似于广告弹窗的效果;
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>setInterval案例</title> </head> <style type="text/css"> #content{ position:relative; height: 500px; width: 500px; background-color: #666; } #one{ position: absolute; top: 0px; left: 0px; height: 100px; width: 100px; background-color: red; font-size: 50px; line-height: 50px; text-align: right; color: #fff; } </style> <body> <div id="content"> <div id="one"><div id="close">X</div></div> </div> <p>距离国庆节还有</p> <script> var content = document.getElementById('content'); var one = document.getElementById('one'); var close = document.getElementById('close'); var x=0; var y=0; var xs=10; var ys=10; function scroll(){ x += xs; y += ys; if(x >= content.offsetWidth-one.offsetWidth || x <= 0){ xs = -1 * xs; } if(y >= content.offsetHeight-one.offsetHeight || y<=0){ ys = -1 * ys; } one.style.left = x + 'px'; one.style.top = y + 'px'; } var dt = setInterval(scroll, 100); one.onmouseover = function(){ clearInterval(dt); }; one.onmouseout = function(){ dt = setInterval(scroll,100); }; close.onclick = function(){ one.style.display = 'none'; } </script> </body> </html>
期待!!!