20

I want to make a banner by using jQuery. When the page loaded script will show a group of photos one by one. For example, the controller sends 10 photos and each photo will be shown in 30 seconds after 10 minutes the script demand another photo from the controller.

The question is: How can I make a function that runs in 30 sec. I need to run a function in a time interval without any button click or anything else.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sesen
  • 362
  • 2
  • 4
  • 17
  • https://developer.mozilla.org/en/DOM/window.setTimeout and https://developer.mozilla.org/en/DOM/window.setInterval – Felix Kling May 21 '11 at 11:35

4 Answers4

48

The main method is:

 setInterval(function () {
        console.log('it works' + new Date());
    },30000);

If you need to clear interval in future:

var myInterval = setInterval(function () {
            console.log('it works' + new Date());
        },30000); 

in the future:

clearInterval(myInterval);
Roki
  • 2,680
  • 1
  • 22
  • 21
4

Try something like this:

HTML:

<ul id="ticker">
    <li>Image 1</li>
    <li>Image 2</li>
    <li>Image 3</li>
    <li>Image 4</li>
    <li>Image 5</li>
</ul>​

CSS:

ul{height:20px; overflow:auto}​

JS:

var $ticker = $('ul#ticker');
var speed = 300;
var pause = 3000;

var tick = function () {
    var first = $ticker.find('li').first().animate({
        height: 0
    }, speed).hide('normal', function() {
        $(this).remove();
        $ticker.append('<li>' + first + '</li>');
    }).html();
};

$('ul#ticker').click(tick);
setInterval(tick, pause);

Here, a simple Demo.

yckart
  • 32,460
  • 9
  • 122
  • 129
0

JavaScript provides a setTimeout function:

var timeoutID = window.setTimeout(code, delay);
Travis
  • 12,001
  • 8
  • 39
  • 52
BnW
  • 592
  • 1
  • 3
  • 13
-2

You should use setInterval like this

setInterval( "alert('Hello')", 5000 );
Amit
  • 21,570
  • 27
  • 74
  • 94
  • 1
    It is strongly preferable to use a function or closure as first argument, not a string. – vog Aug 12 '16 at 15:16