定时器和延迟问题

时间:2016-10-18 18:31:14

标签: jquery

我有一个脚本功能,允许图像在4个图像之间旋转。页面加载时该函数有2秒超时,然后等待8秒再旋转到第二个(以及后续图像)

我需要做的是设置它以便图像在加载后立即开始旋转,然后在此之后旋转8秒。

这是jsfiddle



    $(function(){
    	$('.fadein2 > :gt(0)').hide();
    	setTimeout(function() {
    	setInterval(function(){$('.fadein2 :first-child').fadeOut().next().fadeIn().end().appendTo('.fadein2');}, 8000);
    	}, 2000);
    });

    .fadein { 
    	position:relative; 
    	height:400px; 
    	width:300px;
    	float: left;
    	padding: 5px; 
    }
    .fadein > * { 
    	position:absolute; 
    	left:0; 
    	top:0; 
    	display:block;
    	padding: 5px;
    }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
  <a href="/ContractHome.html">
    <div class="fadein" style="padding: 15px;">
      <img src="http://www.view-restaurant.co.uk/uploads/1/1/9/4/11949146/2826626.jpg?902" alt="">
      <img src="http://d.otcdn.com/imglib/hotelfotos/8/203/hotel-hamilton-island-reef-view-whitsunday-islands-hamilton-island-018.jpg" alt="">
      <img src="http://www.view-restaurant.co.uk/uploads/1/1/9/4/11949146/2826626.jpg?902" alt="">
      <img src="http://d.otcdn.com/imglib/hotelfotos/8/203/hotel-hamilton-island-reef-view-whitsunday-islands-hamilton-island-018.jpg" alt="">
    </div>
  </a>
  <p class="hoverText" style="top: 100px;width: 100%;">Contract</p>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

我想我解决了你的问题。 您需要两次调用您的函数,一个在setTimeout,第二个在setInterval

setInterval 是你的长时间(你打电话给你)

setTimeout 为你的开始时间(你很快就会打电话)。

Fiddle

上更新您的代码

,此处:

$(function() {
  $('.fadein > :gt(0)').hide();
  setTimeout(function() {
    setInterval(function() {
    	fadeInFadeOut()
    }, 8000);
    fadeInFadeOut()
  }, 2000);
});

function fadeInFadeOut(){
	$('.fadein :first-child')
    .fadeOut()
    .next()
    .fadeIn()
    .end()
    .appendTo('.fadein')
}
.fadein {
  position: relative;
  height: 400px;
  width: 300px;
  float: left;
  padding: 5px;
}

.fadein > * {
  position: absolute;
  left: 0;
  top: 0;
  display: block;
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
  <a href="/ContractHome.html">
    <div class="fadein" style="padding: 15px;">
      <img src="http://www.view-restaurant.co.uk/uploads/1/1/9/4/11949146/2826626.jpg?902" alt="">
      <img src="http://d.otcdn.com/imglib/hotelfotos/8/203/hotel-hamilton-island-reef-view-whitsunday-islands-hamilton-island-018.jpg" alt="">
      <img src="http://www.view-restaurant.co.uk/uploads/1/1/9/4/11949146/2826626.jpg?902" alt="">
      <img src="http://d.otcdn.com/imglib/hotelfotos/8/203/hotel-hamilton-island-reef-view-whitsunday-islands-hamilton-island-018.jpg" alt="">
    </div>
  </a>
  <p class="hoverText" style="top: 100px;width: 100%;">Contract</p>
</div>