Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a function every 3 seconds for 15 seconds?

How do I call a jQuery function every 3 seconds?

$(document).ready(function ()
{
    //do stuff...

    $('post').each(function()
    {
        //do stuff...
    })

    //do stuff...
})

I'm trying to run that code for a period of 15 seconds.

like image 784
Jonas Avatar asked Jan 24 '12 17:01

Jonas


People also ask

How do you call a function every 15 seconds?

setInterval( function () { check_alive_status(); }, 15000 // every 15 seconds );

How do you call a function after every second?

The setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed. 1 second = 1000 milliseconds.

How do you call a function repeatedly every 5 seconds in JavaScript?

The setInterval() method in JavaScript can be used to perform periodic evaluation of expression or call a JavaScript function.

How do you call a function after 2 seconds react?

The setTimeout method allows us to run a function once after the interval of the time. Here we have defined a function to log something in the browser console after 2 seconds. const timerId = setTimeout(() => { console. log('Will be called after 2 seconds'); }, 2000);


2 Answers

None of the answers so far take into account that it only wants to happen for 15 seconds and then stop...

$(function() {
    var intervalID = setInterval(function() {
        //  Do whatever in here that happens every 3 seconds
    }, 3000);
    setTimeout(function() {
        clearInterval(intervalID);
    }, 18000);
});

This creates an interval (every 3 seconds) that runs whatever code you put in the function. After 15 seconds the interval is destroyed (there is an initial 3 second delay, hence the 18 second overall runtime).

like image 185
Reinstate Monica Cellio Avatar answered Oct 24 '22 04:10

Reinstate Monica Cellio


You can use setTimeout to run a function after X milliseconds have passed.

var timeout = setTimeout(function(){
    $('post').each(function(){
        //do stuff...
    });
}, 3000);

Or, setInterval to run a function every X milliseconds.

var interval = setInterval(function(){
    $('post').each(function(){
        //do stuff...
    });
}, 3000);

setTimeout and setInterval return IDs, these can be used to clear the timeout/interval using clearTimeout or clearInterval.

like image 44
Rocket Hazmat Avatar answered Oct 24 '22 04:10

Rocket Hazmat