set time out not working with function - javascript

I am using the following to pause the javascript for a few seconds:
setTimeout(start_countdown(),3000);
It does not work, the function is called regardless of the seconds. The following function does however work, which doesnt use a function.
setTimeout(alert('hi'),3000);
How can I solve this?

You need to pass a function reference. You are passing a function's return value.
The difference is this: one is a blueprint of the function you want to happen, the other means you are executing the function immediately and passing its return value to setTimeout.
setTimeout(start_countdown, 3000);
If you want to do something more complex than simply call a named function, OR you want to pass a param to the named function, you'll need to instead pass an anonymous function to the timeout and call your function within that:
setTimeout(function() {
start_countdown(/* possible params */);
/* other code here as required */
}, 3000);

If you dont need to pass params dont use ()
setTimeout(start_countdown,3000);
If you do you have to wrap your function
setTimeout(function(){start_countdown(parameter)},3000);

write instead
setTimeout(start_countdown, 3000);
without parens ()
the second example could be also written as
setTimeout(function() { alert('hi'); }, 3000);

In different browsers it works in different way. In IE you need to use the anonymous function to pass the parameters to the callback:
setTimeout(function(){alert('hi')},3000);

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

Calling javascript functions without parenthesis

When i was reading some code of jquery then i found this in one of their widgets
option: {
_page: this._getPage,
_panelInner: this._getPanelInner()
},
_getPage : function(){ //code goes here that returns something..},
_getPanelInner : function(){ //code goes here that returns something..}
I wanna know how's the first this._getPage function is being called without parenthesis. And if functions can be called like this then why the next function _getPanelInner is being called with parenthesis..?
_panelInner will hold the value returned by the _getPanelInner function while _page will hold a reference to the _getPage function. This means that the function would be able to be called in one of the following ways:
option._page()
this._getPage()
Both of these function calls would execute the same function but that function is not called automatically (according to the code that is displayed).
It's not getting called, it's only having a reference to the function so later you can do:
option._page();

How to make call to a JavaScript promise cleaner?

I have the following call to a Javascript promise:
deleteDatabase().then(function () {
doSomeStuff();
}, function (err) {
processError(err);
});
It works fine, but it looks really wordy. Is there a way to have a terser way to do this? Maybe something like this (which does not seem to work):
deleteDatabase().then(doSomeStuff(), processError(err));
You need to pass a function, not the result of calling them:
deleteDatabase().then(doSomeStuff, processError);
Of course, this will pass the result of the deleteDatabase() action to your doSomeStuff function, so if you expect it to get no arguments you will need to use the function expression as you did.
You have an issue with the syntax
deleteDatabase().then(doSomeStuff, processError);
if you put () after the function name it will call it immediately, by omitting the parenthesis you are passing a reference to the function and asking for it to be called at some point later on by the promise.

Delay 6 seconds before beginning a function that will loop itself, small, not working, why?

I'm trying to create a 6 second delay before the heartColor(e) function begins, the function will then continue to loop. I don't understand why it's starting the function immediatley, and not waiting the 6 seconds it's supposed to, what did I do wrong?
function heartColor(e) {
e.animate({
color: '#7ea0dd'
}, 1000).animate({
color: '#986db9'
}, 1000).animate({
color: '#9fc54e'
}, 1000, function(){
heartColor(e)
})
}
$('.something').hover(function(){
setTimeout(heartColor($(this)), 6000);
})
The setTimeout() function expects its first parameter to be a function reference (or a string, but that's not recommended for several reasons). You are not passing it a function reference, you are calling the heartColor() function and passing the result to setTimeout(). So the function executes immediately, and then after six seconds nothing happens because the return value was undefined so setTimeout() had nothing to work with.
Try this instead:
$('.something').hover(function(){
var $this = $(this);
setTimeout(function() {
heartColor($this);
}, 6000);
})
The reason I have included an anonymous function as the parameter to setTimeout is that your call to heartColor() needs to pass a parameter through. If it didn't have any parameters you could do this:
setTimeout(heartColor, 6000);
Note there are no parentheses after heartColor - that gets a reference to the function without calling it so that later setTimeout calls it for you. But you can't get a reference to the function and provide parameters at the same time so you need to wrap the call up in another function. You could do this:
var $this = $(this);
function callHeartColor() {
heartColor($this);
}
setTimeout(callHeartColor, 6000);
My original answer with the anonymous function is kind of short hand for that and (most people find it) more convenient.
The reason I have created a variable $this is because of the way the this keyword works in JavaScript, which depends on how a function is called. If you simply said heartColor($(this)) inside the anonymous function (or the callHeartColor() function) this would not be the element being hovered over.
you are invoking the function heartColor instead of passing it as a parameter. you have to do:
$('.something').hover(function(){
setTimeout(function(){heartColor($(this))}, 6000);
})
You want this:
$('.something').hover(function(){
setTimeout(function() {heartColor($(this));}, 6000);
})

Why is function() needed sometimes in JavaScript?

HTML
<button id='hello'>Click Me!</button>
JavaScript (wrong)
$('#hello').click(alert('Hello, World!'));
JavaScript (correct)
$('#hello').click(function() {
alert('Hello, World!');
}
I'm wondering why the first JS code triggers on the event load instead of click. Can anyone tell me why function() { [code] } is needed for the script to work properly?
In this example, I used jQuery events, but this is not specific to it, for example, I need to use it with setTimeout, too.
The click function expects another function as a parameter.
In the first case you would be passing the result of calling alert('hello world');, which is null.
The second is just a shorthand for:
$('#hello').click(callback);
function callback(){
alert('hello world');
}
Because .click() is a handler. The first argument is a function to assign. But if you actually pass the function with arguments then it will call the function (in this case alert) and then pass it's return value.
Writing $('#hello).click( function() { } )` is basically a short hand for writing:
var myfunction = function() {
// code
};
$('#hello').click( myfunction );
As you can see in the long hand way, it's passed as a reference to the function instead of the function's return value.
Your first example says "evaluate
alert('Hello, World!')
right now, and pass the result as an argument to click. "
The second says "Define a function which will do the alert when I call it, and pass that whole function as an argument to click.
The function() { ... } syntax is how you declare an anonymous function in Javascript. jQuery uses lots of these to specify that some action will be performed later, like when an event occurs. You can think of it as delaying the execution of your function until necessary. Without this syntax, whatever code you place there is evaluated immediately, which is not what you want for an event handler.
You might think, "why isn't JavaScript smart enough to know the difference?" Consider this:
function returnCallback(linkId, data) {
return function(e) {
alert('Clicked on ' + linkId + '. Here is some data: ' + data);
// Maybe do some stuff with e, the event parameter
}
}
$('#some-link').click(returnCallback('some-link', 'some-data'));
$('#other-link').click(returnCallback('other-link', 'different-data'));
This is a contrived example, but it illustrates the power of anonymous functions and closures. This works since returnCallback returns a function.
In the first instance, "JavaScript wrong", you're actually calling alert('Hello, World!') at the point that the script is loaded. Now, the reason you pass the .click function a function is because it can call it at any point. Essentially, you're packing code together to be run (or not run at all) at any point when you put it in a function.
$('#hello').click(alert('Hello, World!')); is attempting to run alert('...') and pass its return value to the .click() function which will not work as expected.
This is because JavaScript evaluates everything and during this process your alert is invoked. You can use anonymous function or you can also use your own custom function as implemented below:
<script language="javascript" type="text/javascript">
$("#mybutton").click(clickFired);
function clickFired() {
alert('click fired');
}
</script>
The parameter required for the .click() function is a Function. Therefore $("#hello").click(function { [code] }); is required. Because there's nothing to return by alert().
The click function here assigns a value to the event handler.
With the first ("wrong") code you're assigning a value of alert('Hello, World!') which is itself a function call, so it's going to be immediately evaluated and hence appear at load.
With the second ("correct") code you're now assigning a new anonymous function which is not executed itself, just instantiated at load. Hence this will work as expected later.
somefunction(alert('hello! world'));
this would mean you want to pass to somefunction the return value of alert("hello! world").
jquery click expects a callback that it should fire upon click on the element. so you put it in a function which does not execute unless someone (here jquery) calls it explicitly.

Categories