Js定时器
设置定时器分为两种:
一种是setTimeout(只实现一次),一种是setInterval(反复执行)
删除定时器:clearTimeout 或者clearInterval
下面demo是用定时器实现一个图片移动的效果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box{
width: 100px;
height: 100px;
background: greenyellow;
position: fixed;
left:0px;
top:100px;
}
</style>
<script>
/* 获取容器Id-->设置定时器-->设置初始位置-->设置移动距离--->定义函数-->将移动距离赋值给容器的位置 */
window.onload = function(){
var oDiv = document.getElementById('box');
var oTimer = setInterval(fnMove,30);
var iLeft = 0;
var iSpeed = 3;
function fnMove(){
iLeft += iSpeed;
oDiv.style.left = iLeft + "px";
if(iLeft > 600){
iSpeed = -3;
}