This question already has answers here:
Jquery setInterval() not working
(5 answers)
Closed 9 years ago.
In my javascript I have:
$(document).ready(function ()
{
setInterval(test('test alert'), 10000);
});
function test(value)
{
alert(value);
}
Simple, when the document is ready, it should set up the setInterval... Which basically means, wait 10 seconds, run the function, then repeat every 10 seconds.
The problem is the setInterval is not activating properly. The test function is being fired immediately (instead of waiting 10 seconds), and never fires again subsequent times. What am I doing wrong here?
Now, if I set up my setInterval as follows, it works fine... but why?
setInterval(function() { test('test alert'); }, 10000);
That's because you're passing the return value of invoking the function, not the function itself. What you want is this:
setInterval(test, 10000);
If you need to pass an argument into the test, you have to wrap it in another function:
setInterval(function(){test('test alert');}, 10000);
Whenever you use a literal followed by parenthesis (like test() or test('test alert'), the parentheses are a signal to JavaScript to invoke the function. To test this for yourself, try the following in an interactive console in your browser:
console.log('test: ' + test);
console.log('test(): ' + test());
The first will tell you that the value is a function; the second will tell you undefined; that's because the function (test) has been invoked, and the value returned.
Note that in JavaScript, functions are first-class citizens, so there's nothing wrong with creating a function that itself returns a function:
function test(value) {
return function(){
alert(value);
}
}
If you did that, your setInterval would work as you originally expected it to:
// test('test alert') returns a function
setInterval(test('test alert'), 10000);
setInterval() expects a function or an eval()-able string as its first argument. In your code, you are passing it the return value of the function test()
Instead it should be:
setInterval(function() {
test('test alert');
}, 10000);
Related
How come I can say:
var myFunction = function() {
setTimeout(myFunction, 1000);
}
myFunction();
Why does the function call in the setTimeout not require parentheses, but the last line does?
Nutshell
myFunction references the function
myFunction() calls the function
More Words
setTimeout expects a function reference* as an argument.
There are circumstances where setTimeout(myFunction(), 1000) might make sense, like if myFunction() returns a function, e.g.
function myFunction() {
return function() {
alert("ohai")
}
}
// Or
const myFunction = () => () => alert("ohai")
So:
setTimeout(myFunction(), 1000);
setTimeout gets the return value of myFunction
myFunction returns a function (that calls alert)
meaning there will be an alert every second.
See also Why function statement requires a name?
* Or a string to be evaluated, but a reference is preferred.
myFunction is a function
myFunction() calls the function and yields whatever value the function returns.
The purpose of setTimeout is running code after some time elapses. You need to pass just the function to it (so setTimeout can itself call the function when appropriate) because if you called the function (with the parenthesis) before passing it to setTimeout it would execute now instead of after 1 second.
When you use the parenthesis, it's saying 'call this function now'. So if you say setTimeout(myFunction(),1000);, it will use the return value of the function as the callback for the timeout. If the return value for the function is not itself a function, you'll get an error because it will try to execute something that isn't executable after the timeout (a string, a number, undefined, etc).
In line 2, the function myFunction is not called, but passed as an argument to the setTimeout function, whereas in line 4 myFunction is called; to call a function, you always have to use parentheses, even if there are no arguments.
I think this example would make it clearer if i may,
function callback() {
console.log('this function runs on page loads.');
}
setTimeout(callback(), 2000);
Here callback() function will run immediately after page loads and won't wait 2 seconds.
function callback() {
console.log('this function runs after page loads.');
}
setTimeout(callback, 2000);
Here callback() function will run after 2 seconds.
This question already has answers here:
Why is the method executed immediately when I use setTimeout?
(8 answers)
Closed 2 years ago.
Can anyone explain why this is happening. I have created a function in JS and trying to call it after 60 seconds using setTimeout function. But it runs right away after the page loads. Why is this happening and setTimeout is not delaying the function code? Below is the code.
<script>
function first()
{
document.getElementById('addProductText').style.color="#32A067";
}
setTimeout(first(),60000);
</script>
Use your call to the function without the brackets ():
setTimeout(first, 6000);
This way you are referencing to the function, and not calling it immediately.
Working example:
function first() {
document.getElementById('addProductText').style.color = "#32A067";
}
setTimeout(first, 6000);
<div id="addProductText">Hello World!</div>
You should only pass the name of the function without calling it:
function first(){
console.log("Hello")
}
setTimeout(first, 60000);
I'm trying to run a function every 5 seconds using JavaScript using a recursive setInterval function.
The following code just logs "started" as fast as possible and then crashes the browser. Why is this not running every 5 seconds?
function five() {
console.log("five");
setInterval(five(), 5000);
}
five();
Don't use setInterval this way. Use setTimeout. By calling setInterval, you create a UNIQUE timer every time the function is called. SetTimeout would create one timer that ends, and then creates a new timer.
You should also change the way you reference five. five() executes the function immediately. Just five passes a function reference, so do it as you see below.
function five() {
console.log("five");
setTimeout(five, 5000);
}
five();
Of course, you can always pass the function call as a string to be evaluated:
setTimeout("five()", 5000); // note the quotes
But this is generally considered bad practice.
You're calling five immediately, instead of merely passing it in:
function five () {
console.log("five");
}
setInterval(five, 5000);
/* ^ */
Change this line:
setInterval(five(), 5000);
like this:
setInterval(five, 5000);
But seems like what you really need is:
setTimeout(five, 5000);
So your code will look like:
function five() {
console.log("five");
setTimeout(five, 5000);
}
five();
The reason of crashing it is that you are calling the function five. Instead of that you should pass it as parameter.
setInterval(five, 5000);
I am getting into sort of confusion here. Please go through the below code,
<script>
setInterval(function1,3000);
setInterval(function2(),3000);
function function1() {
console.log("Function1 called....");
}
function function2() {
console.log("Function2 called....");
}
</script>
As you can see I have two setInterval functions one calls function like function1 and another function2(). The output of first is perfect that gets called every 3sec and first call after 3sec. But second one gets called without the delay i.e function2.
I guess that () might be doing things there but I'm not sure about what I'm missing there. I just want to know what is happening there.
setInterval(function1,3000); instructs the JS engine to execute the function function1 every 3 seconds.
setInterval(function2(),3000); instructs the JS engine to run function2 once, then run the return value every 3 seconds. This return value is empty.
For a bit of fun try
function function2() {
console.log("Function2 called....");
return "function3();"
}
function function3() {
console.log("Function3 called....");
}
setInterval(function2(),3000);
Edit
In reponse to #harsha's comment: What do I mean by "run the return value"
setInterval(function2(),3000); will trigger the following workflow:
Initiate executing function2() (execute it, because it the brackets are given).
function2 runs to completion, then returns.
In your OQ, there is no return value from the function so it is null
The return value of my function2 is the string "function3();"
This return value is now inserted into the setInterval() call
The OQ version results in setInterval(null, 3000);, which does nothing every 3 seconds
My version results in setInterval("function3();", 3000), which calls eval("function3();"); every 3 seconds, which in turn runs function3 every 3 seconds.
In the second setInterval you are executing it right away and plugging the value returned by that function into setInterval.
For example,
setInterval(a(), 5000);
function a(){
return function(){
console.log("Executed!");
};
};
a() executed and returning the function into setInterval. You should see the console is writing Executed every 5 seconds.
This is just like math:
f(x) = x + 1
g(x) = 2
f(g(2)) = g(x) + 2 = 4
You replace g(2) with whatever it returns
(you replace a() with the function in this case)
http://jsfiddle.net/DerekL/39wNn/
The () makes the function get executed immediately in the second case. In the first case, just the pointer to function which gets executed later as the call back function.
This question already has answers here:
Why is the method executed immediately when I use setTimeout?
(8 answers)
Closed 2 years ago.
Consider the following example:
<script type="text/javascript">
function alertBox(){
alert('Hello World!');
}
function doSomething(){
setInterval(alertBox(), 5000); //This is for generic purposes only
};
function myFunction(){
setTimeout(doSomething(),3000);
};
myFunction();
</script>
What is it that causes this to execute IMMEDIATELY, rather than waiting the 3 seconds set, as well as only executing the alert ONCE, rather than at the scheduled 5 second intervals?
Thanks for any help you can provide!
Mason
alertBox()
Doesn't this look like an immediate function call?
Try passing the function (without executing it) instead:
setInterval(alertBox, 5000);
its because you are executing the function, not passing a function object.
function myFunction(){
setTimeout(doSomething, 3000); // no () on the function
};
Following codes executing differently,
setTimeout(console.log('Nuwan'),0)---(A); and
setTimeout(function(){console.log('Nuwan'),0}) --- (B)
The reason is when (B) is executing, CallStack in javascript runtime push the setTimeout() to web API and
WebAPI waits 0 seconds to push the callback function to the event queue and then EventLoop pushes the callback to the stack after the current stack is empty.
In Case (A), console.log() directly calling because it is in the WepAPI, no need to go for an event loop to execute.
More Ref:
WebAPIs: https://developer.mozilla.org/en-US/docs/Web/API/Console_API
Javascript Runtime and Event Loop: https://cybrohosting.com/knowledgebase/17/How-JavaScript-works-in-browser-and-node.html