14-定时器
在JS中的定时器分为两种 : 1 , setTimeout() 2 , setInterval()
1 , setTimeout()
语法 : setTimeout(函数,时间差)
只在指定时间后执行一次
应用 : 数据交互的时候 , 如果数据阻塞了 , 可以考虑 加一个一次性定时器来处理
定时器 异步运行
function hello() { alert("hello"); } var t1 = window.setTimeout(hello,2000); var t2 = window.setTimeout(hello(),4000); // 使用字符串方法 window.clearTimeout(t1); //去掉定时器
window.clearTimeout(函数名) 清除定时器
2 . setInterval()
语法 : setInterval("执行的函数" , 时间差)
在指定时间为周期循环执行
应用 : 可以做动画
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> #box{ width: 100px; height: 100px; background-color: red; } </style> </head> <body> <button id="start">开启定时器</button> <button id="clear">清除定时器</button> <div id="box"></div> <script> var count = 0; var timer = null; document.getElementById('start').onclick = function() { var oDiv = document.getElementById('box'); clearInterval(timer); timer = setInterval(function() { count+=10; oDiv.style.marginLeft = count + 'px'; }, 50) }; </script> </body> </html>
两种方法根据不同的场景和业务需求择而取之,
对于这两个方法,需要注意的是如果要求在每隔一个固定的时间间隔后就精确地执行某动作,那么最好使用setInterval,而如果不想由于连续调用产生互相干扰的问题,尤其是每次函数的调用需要繁重的计算以及很长的处理时间,那么最好使用setTimeout