Run a function in time interval in jQuery

2020-01-29 09:33发布

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.

4条回答
劳资没心,怎么记你
2楼-- · 2020-01-29 10:10

You should use setInterval like this

setInterval( "alert('Hello')", 5000 );
查看更多
小情绪 Triste *
3楼-- · 2020-01-29 10:12

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);
查看更多
兄弟一词,经得起流年.
4楼-- · 2020-01-29 10:15

JavaScript provides a setTimeout function:

var timeoutID = window.setTimeout(code, delay);
查看更多
男人必须洒脱
5楼-- · 2020-01-29 10:20

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.

查看更多
登录 后发表回答