setInterval 定时器的使用

时间:2022-11-01 00:06:05
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>setInterval方法的使用</title> <style> div{ width: 200px; height: 200px; background-color: red; position: absolute; top:50px; } </style> </head> <body> <button>点我</button> <div></div> <script> function $(selector){ return document.querySelector(selector); } var num = 0; $('button').onclick = function(){ //开启定时器,占内存 var Timer = setInterval(function(){ if (num > 600){ //停止定时器  clearInterval(Timer) } num += 20; $('div').style.left = num + 'px'; },100); }; </script> </body> </html>