Auto-execute parenthesis creates problems with setInterval? - javascript

setInterval(function () {myFunction()}, 1000);
(function myFunction() {
...
})();
The parenthesis around the function make it run automatically. However, it causes problems with setting the interval for that function. Is there any way to fix this? Or, perhaps, a better way to make functions run automatically?
Thank you in advance.

You've created an IIFE, and the name of the function is only accessible inside the function, to the interval call, myFunction is not defined.
If you want to create a function, and then run it right away and in an interval, you just do that
function myFunction() { // make pretty function
...
};
setInterval(function () {
myFunction(); // make pretty function run each second
}, 1000);
myFunction(); // make pretty function run now

Related

setTimeout nuances in Node.js

I'm trying to understand how the callback function works inside the setTimeout function. I'm aware the format is: setTimeout(callback, delay) I wrote a little test script to explore this.
test1.js
console.log("Hello")
setTimeout(function () { console.log("Goodbye!") }, 5000)
console.log("Non-blocking")
This works as expected, printing Hello <CRLF> Non-blocking and then 5 seconds later, prints Goodbye!
I then wanted to bring the function outside of the setTimeout like this:
console.log("Hello")
setTimeout(goodbye(), 5000)
console.log("Non-blocking")
function goodbye () {
console.log("Goodbye")
}
but it doesn't work and there isn't a 5 second delay between Non-blocking and Goodbye!, they print straight after each other.
It works if I remove the brackets from the function call in the timeout, like this:
setTimeout(goodbye, 5000)
but this doesn't make sense to me because that's not how you call a function. Futhermore, how would you pass arguments to the function if it looked like this?!
var name = "Adam"
console.log("Hello")
setTimeout(goodbye(name), 5000)
console.log("Non-blocking")
function goodbye (name) {
console.log("Goodbye "+name)
}
My question is really, why doesn't it work when there are parameters in the function, despite the fact the setTimeout is being provided with a valid function with the correct syntax?
By putting the parentheses after your function name, you are effectively calling it, and not passing the function as a callback.
To provide parameters to the function you are calling:
You can pass an anon function. setTimeout(function(){goodbye(name)}, 5000);
Or, you can pass the arguments as a third parameter. setTimeout(goodbye, 5000, name);
Look at this question: How can I pass a parameter to a setTimeout() callback?
No matter where you place it, goodbye(name) executes the function immediately. So you should instead pass the function itself to setTimeout(): setTimeout(goodbye, 5000, name).
When you use it like this:
setTimeout(goodbye(), 5000);
it will first call goodbye to get its return value, then it will call setTimeout using the returned value.
You should call setTimeout with a reference to a callback function, i.e. only specifying the name of the function so that you get its reference instead of calling it:
setTimeout(goodbye, 5000);
To make a function reference when you want to send a parameter to the callback function, you can wrap it in a function expression:
setTimeout(function() { goodbye(name); }, 5000);
You can use parantheses in the call, but then the function should return a function reference to the actual callback function:
setTimeout(createCallback(), 5000);
function createCallback() {
return function() {
console.log("Goodbye");
};
}

Can javascript's 'setInterval' be configured to trigger immediately, and with an interval?

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()

Is self-calling functions in Javascript harmful?

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);
}

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 ?
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);

Call an anonymous function defined in a setInterval

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.

Categories