user2840278
user2840278

Reputation: 281

Jquery setInterval execute on page load

Helllo, I have a function that needs to be executed every 10 seconds. It works like this:

setInterval(function () {

}, 10000);

The problem is that I need this function to be executed once on page load - now the first execution happens only after 10 seconds. Is it possible to do what I want with setInterval, or is there another function?

Thank you for your time!

Upvotes: 2

Views: 9746

Answers (4)

Ja͢ck
Ja͢ck

Reputation: 173662

This is the most obvious way:

var myFunction = function() {

};

myFunction();
setInterval(myFunction, 10000);

Alternatively, use setTimeout():

(function foo() {
    // do stuff here
    setTimeout(foo, 10000);
})();

Upvotes: 5

cssyphus
cssyphus

Reputation: 40106

There may be a better way, but this will work:

$(document).ready(function() {
    var readyNow = 0;

    //Runs immediately, waiting ten secs before setting flag to true
    setTimeout(function(){
       readyNow++;
    },10000);

    //Starts immediately, but flag won't be true for first ten seconds
    setInterval(function () {
        if (readyNow==1) {
            //do your code
        }
    }, 10000);

}); //END document.ready()

Upvotes: 2

Bas van Dijk
Bas van Dijk

Reputation: 10713

You need to name the function which you want to execute like:

function myFunction() {

}

setInterval(myFunction, 10000);

Here is myFunction the function that is executed every 10 seconds. The call on the last line

Upvotes: 1

SQRCAT
SQRCAT

Reputation: 5840

Try this:

<script type="text/javascript">

    var fnc=function(){
        /* do your stuff here */
        setTimeout(fnc, 1000);
    };

    $(document).ready(function(){
        fnc();
    });

</script>

Upvotes: 1

Related Questions