如何使函数每隔30秒运行一次


How do i make a function run every 30 seconds or something?

嗨,我正在让我的背景图像随机出现。但现在我希望它每30或40秒改变一次图像。现在我的代码是这样的:

#background{
  position: fixed;
  height: 100%;
  width: 100%;
  z-index: -100px;
<?php
  $count = rand(1, 8);
  $hello = "background: url('img/backImg/". $count ."') center center;"; 
  echo ($hello);
?>
  background-repeat:no-repeat;
  background-color:   #d8d8d8;
  background-size: cover;
}

所以我希望$count字符串每30秒取一个随机数。

jQuery Cycle插件是一个幻灯片插件,支持许多不同类型的过渡效果。它支持悬停时暂停、自动停止、自动调整、前/后回调、点击触发器等等。

您可以将timeoutdelay设置为30秒。

您可以在javascript的帮助下完成此操作。它将每30秒调用一次这个函数

var myVar=setInterval(function(){myTimer()},30000);
function myTimer(){
    // your code to change the background image url 
    // you can do that with $('#background').attr('style',"your css") or  
    // $('#background').css('background-url',"your path") 
}
<pre> 
<script type="text/javascript">
  $(document).ready(function counter() {
     randomNumber=Math.floor(Math.random() * 8) + 1; //make random number between 1-8
     $(this).css("background-image", "url('img/backImg/" + randomNumber + ".png')");
     setTimeout("counter()",30000); play function counter after 30s
  });//end the $(document).ready
</script>
</pre>

试试这个代码,我希望它能帮助你。

当你的页面准备好工作时,这个功能就会启动,并生成一个1-8之间的随机数,然后更改你的背景图像,并在30秒后进行增益你只是设置了你的替代这个。