Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a function in time interval in jQuery

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.

like image 538
Sesen Avatar asked May 21 '11 11:05

Sesen


People also ask

How do you call a function every 5 seconds in jQuery?

To make a jQuery function call after “X” seconds, use the siteTimeout() method.

How do I call a function after 2 seconds in jQuery?

To call a jQuery function after a certain delay, use the siteTimeout() method. Here, jQuery fadeOut() function is called after some seconds.

How call a function in jQuery every minute?

Answer: Use the JavaScript setInterval() method You can use the JavaScript setInterval() method to execute a function repeatedly after a certain time period. The setInterval() method requires two parameters first one is typically a function or an expression and the other is time delay in milliseconds.

How can we call a function automatically after waiting for some time in jQuery?

In order to run a function automatically after waiting for some time, we are using the jQuery delay() method. The . delay() method in jQuery which is used to set a timer to delay the execution of the next item in the queue.


2 Answers

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);
like image 54
Roki Avatar answered Oct 18 '22 03:10

Roki


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.

like image 42
yckart Avatar answered Oct 18 '22 03:10

yckart