setInterval,setTimeout详解、定时器管理

fwxstar 2018-06-29 698次浏览

摘要: //定时器:时间概念 // var timer=setInterval(函数 ,毫秒);   重复执行 // clearInterval(&...
//定时器:时间概念
// var timer=setInterval(函数 ,毫秒);   重复执行
// clearInterval( timer )   清除定时器
//  vat time = setTimeout(函数 ,毫秒);   执行一次
// clearTimeout( timer )   清除定时器


var imgUrl=['https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1530248264122&di=070f1a2a8b4836bf2e7655eaecf525cc&imgtype=0&src=http%3A%2F%2Fup.enterdesk.com%2Fedpic_source%2Fa2%2F7a%2F95%2Fa27a957696c16e93f6a75540abef0a8b.jpg'
   ,'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1530248302522&di=5f940812d376cadab28ce6fd9bb9138d&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F1%2F57b81a4f91110.jpg',
   'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1530248306412&di=063c1781ad568833bca1db7add5277b1&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F3%2F573444a1afb96.jpg'];


//setInterval
var timer= null;
var num=0;
function change(){
   document.body.style.background= "url("+imgUrl[num]+")";
   num++;
   num%=imgUrl.length;
}
$("btn1").onclick = function () {
   clearInterval(timer);
   timer=setInterval(change , 1000);
};
$("btn2").onclick = function () {
   clearInterval(timer);
};

//setTimeout
var timer2=setTimeout(function () {
   $("ss").style.display="block";
   setTimeout(function () {
      $("ss").style.display="none";
   },2000);
},1000)