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 ?
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?
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
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.
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);
Related
If I want to trigger an event regularly I use something like (coffeescript):
setInterval (() => myFunction()), 300000
But often I want myFunction called immediately, AND regular intervals thereafter. At present I do this by calling both setTimeout and setInterval, e.g.,
setTimeout (() => myFunction()), 0
setInterval (() => myFunction()), 300000
or
myFunction()
setInterval (() => myFunction()), 300000
Can setInterval be used to do this in one step?
If your function is able to return itself, then yes.
function myFunction() {
// do some work
return myFunction;
}
setInterval(myFunction(), 300000);
I'll let you translate to CS.
So now you're invoking the function instead of passing it to setInterval(). The function runs, and returns itself, which is received by setInterval() and invoked as you'd expect.
I don't know CS, but it looks like you may be passing an anonymous function that invokes your function.
If so, I'm not sure why you're doing that, but it does guarantee that you can take this approach since you don't need to care about the return value of the original.
function myFunction() {
// do some work
}
setInterval(function() {
myFunction();
return myFunction;
}(), 300000);
If there's more work to do in the anonymous function that should run at every interval, then give the function a name and change return myFunction; to return callback;.
function myFunction() {
// do some work
}
setInterval(function callback() {
myFunction();
// some other work
return callback;
}(), 300000);
You can create a custom version of setInterval() that calls the specified function once at the start and then at intervals.
// custom version
window.setIntervalCustom = function(_callback, _delay) {
_callback(); // call once
return window.setInterval(_callback, _delay); // at intervals
};
// this will print 1 once at the start and then at intervals of 1000ms
setIntervalCustom(function() { console.log('1'); }, 1000);
Note: The custom function has been renamed above to avoid any conflict issues with other libs/code thiat might be using the original setInterval()
I have a Javascript function that is calling itself for purpose of refreshing notification bar. My function is like:
function refreshLoop() {
refresh();
setTimeout("refreshLoop();", 10000);
}
My question is that if I use that function like this, will be there any harm -programming error-. I am asking this question because you see refreshLoop() function never ends.
Should I use it like this or do you have any other ideas?
Thanks
This construct is frequent and fine (especially if a conditional call of setTimeout makes it hard to use setInterval), but it's not written as you did. Don't eval code when you can directly pass the function. Use this :
function refreshLoop() {
refresh();
setTimeout(refreshLoop, 10000);
}
You can end the timeout loop by removing the timeout like that:
var timeout;
function refreshLoop() {
refresh();
timeout = setTimeout(refreshLoop, 1000);
}
refreshLoop()
// later on
clearTimeout(timeout)
I don't see anything wrong with it, but you could lose the eval "refreshLoop();"
function refreshLoop() {
refresh();
setTimeout(refreshLoop, 10000);
}
player object has a method stopVideo()
1.False
setTimeout(player.stopVideo, 1000); //says something is undefined
2.True
setTimeout(stopVideo, 1000);
function stopVideo() {
player.stopVideo();
}
What's the difference and why is this happening?
The correct signature for the setTimeout function is as follows:
var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
var timeoutID = window.setTimeout(code, delay);
Your second example works because you are actually defining a function within the setTimeout call.
Your first example is actually the second signature here. So for it to work, you'd have to deal with it as if it was code and pass it as a string (similar to eval() ).
setTimeout( "player.stopVideo()", 1000 );
Here is a link to the resource and an excerpt from the description of the parameters:
func is the function you want to execute after delay milliseconds.
code in the alternate syntax is a string of code you want to execute after delay milliseconds (using this syntax is not recommended for the same reasons as using eval())
If I open the Chrome devtools console and paste in
var player = { stopVideo: function() { console.log('ohai'); }}
setTimeout(player.stopVideo, 1000);
Nothing undefined pops up. I think you need to provide a little more context and a better explanation of what is wrong. Is your stopVideo-function trying to access this?
Both are alias of each other.
This should work:
setTimeout(player.stopVideo(), 1000);
Why 1. doesnt work.
It is because player.stopVideo is not defined before setTimeout(....)
Why 2. works even player is not defined.
when you declare a function stopVideo, the JS engerine will predefine this function at the begining. stopVideo function is defined before setTimeout(...). Thus it's OK.
Another reason why #1 doesnt work:
when you pass player.stopVideo to setTimeout, the "this" object for the method is "window", not "player". So, probably, player.stopVideo wont works.
This is the code from another thread. It activates a function only when the user has stopped typing after a set time.
var keyupTimer;
function keyUpEvent(){
clearTimeout(keyupTimer);
keyupTimer = setTimeout(sendInput,1000); // will activate when the user has stopped typing for 1 second
}
function sendInput(){
alert("Do AJAX request");
}
It works as is. But why does it stop working if I put parenthesis to try to pass variables in this line:
keyupTimer = setTimeout(sendInput,1000); //original code
To
keyupTimer = setTimeout(sendInput(),1000); //with just empty ()
or
keyupTimer = setTimeout(sendInput(var),1000);//or with ('test') or with (var)
with the parenthesis, the delay does not occur and the sendInput function is called immediately. Is this the only format for this particular routine?
TIA
keyupTimer = setTimeout(sendInput,1000); //original code
This says "Run sendInput after 1000ms";
keyupTimer = setTimeout(sendInput(),1000); //with just empty ()
This says "Run sendInput, capture the return value (which should be a function) and run that after 1000ms".
sendInput is a function, sendInput() is a function call.
The first argument for setTimeout is a function reference (i.e. a variable that points to your function). What you provided is a function call. To pass a function with arguments, wrap the function call in an anonymous function. You can pass it directly to setTimeout as an argument since JavaScript functions are first-class objects.
keyupTimer = setTimeout(function() {
sendInput(var);
}, 1000);
In more verbose, that equals to this:
var callback = function() {
sendInput(var);
}
keyupTimer = setTimeout(callback, 1000);
The inline pattern has its advantage that it has access to the scope where the setTimeout is called.
If it fits better to you, you could even create a callback factory to pass a function call to setTimeout as #slebetman pointed out.
function callbackFactory (var) {
return function() {
sendInput(var);
}
};
setTimeout(callbackFactory('some_value'), 1000);
you can try
keyupTimer = setTimeout(function()
{
sendInput('test');
},1000);
so have an anonymous function as parameter for 'setTimeout'
it is also possible to use a string containing javascript code, as a first argument to setTimeout. however, it is strongly discouraged (see comments)
...
/* DON'T DO THIS: */
keyupTimer = setTimeout("sendInput(variable)", 1000)
...
I've made this code:
window.setInterval(function(){ var a = doStuff(); var b = a + 5; }, 60000)
The actual contents of the anonymous function is of course just for this small example as it doesn't matter. What really happens is a bunch of variables get created in the scope of the function itself, because I don't need/want to pollute the global space.
But as you all know, the doStuff() function won't be called until 60 seconds in the page. I would also like to call the function right now, as soon as the page is loaded, and from then on every 60 seconds too.
Is it somehow possible to call the function without copy/pasting the inside code to right after the setInterval() line? As I said, I don't want to pollute the global space with useless variables that aren't needed outside the function.
You can put your callback function in a variable, and wrap up everything in a self-invoking anonymous function:
(function () {
var callback = function() {
var a = doStuff();
var b = a + 5;
};
callback();
window.setInterval(callback, 60000);
})();
No pollution.
This is possible without creating global variables as well:
setInterval((function fn() {
console.log('foo'); // Your code goes here
return fn;
})(), 5000);
Actually, this way, you don’t create any variables at all.
However, in Internet Explorer, the fn function will become accessible from the surrounding scope (due to a bug). If you don’t want that to happen, simply wrap everything in a self-invoking anonymous function:
(function() {
setInterval((function fn() {
console.log('foo'); // Your code goes here
return fn;
})(), 5000);
})();
Credit to Paul Irish for sharing this trick.
Edit: Answer updated with some more information, thanks to bobince.
yet another solution:
(function() {
var a = doStuff();
var b = a + 5;
window.setTimeout(arguments.callee, 60000);
})();
This uses timeout instead of interval so that it can run the first time and then run it's self again after a timeout.