DebelaDevojka
DebelaDevojka

Reputation: 11

Repeat function execution start problem

I repeat execution of function on every second like

setInterval(function(){ /* some code */},1000};

What to change so function would be executed first time immediately and then repeats on every 1 second, any parameter I missed ?

Upvotes: 1

Views: 570

Answers (4)

mqchen
mqchen

Reputation: 4193

An additional solution to the ones already suggested is to return the anonymous function in its declaration, and calling the function immediately after it has been declared.

This way you don't have to use an additional variable and you can still use the interval ID returned by setInterval, which means that you can abort it using clearInterval later.

Eg. http://jsfiddle.net/mqchen/NRQBK/

setInterval((function() {
    document.write("Hello "); // stuff your function should do
    return arguments.callee;
})(), 1000);

Upvotes: 1

kapa
kapa

Reputation: 78671

You can use a self-executing function:

(function Fos () {

     //do your stuff here

     setTimeout(Fos, 1000);

})();

This function will invoke itself, and then set a timeout to run itself again in a second.

EDIT: Just one more note. In my example I used a named function expression (I used the name "Fos"), which allows us to reference the function itself inside the function. Some other examples use arguments.callee, which does not even work in ECMAScript 5 Strict mode, and generally not a recommended practice nowadays. You can read more about it in the SO question Why was the arguments.callee.caller property deprecated in JavaScript?

Upvotes: 5

J. Holmes
J. Holmes

Reputation: 18546

nope. the best you can do is:

var worker = function() { /* code */ }
worker();
setInterval(worker, 1000)

You could use a slightly different pattern like this:

(function() {
    /*code*/
    setTimeout(arguments.callee, 1000);
})()

Note that arguments.callee isn't allowed in strict mode, so then you could do something like:

var worker = function() {
    /*code*/
    setTimeout(worker, 1000);
}
worker();

The latter two code examples will create a function that will call itself 1000 milliseconds after executing. See this link for more details on the differences (advantages/disadvantages) between using setInterval() and setTimeout() chaining.

Upvotes: 2

pimvdb
pimvdb

Reputation: 154818

You might want to declare the function, run it and after that set the interval:

function something() { /* ...  */ } // declare function

something(); // run it now immediately (once)

setInterval(something, 1000); // set an interval to run each second from now on

Upvotes: 2

Related Questions