Simple javascript syntax - javascript

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.

Related

Javascript Callback functions vs just calling functions

So i don't really understand the point of "callback".
Here is an example of callback:
function sayBye(){
alert("Bye!");
}
function saySeeYou(){
alert("See you!");
}
function sayHello(name,myfunc){
alert("Hello");
myfunc;
}
sayHello("Max",saySeeYou());
Whats the point of passing in a function when you can just call the function? like this code does the exact same:
function sayBye(){
alert("Bye!");
}
function saySeeYou(){
alert("See you!");
}
function sayHello(name){
alert("Hello");
saySeeYou();
}
sayHello("Max");
Whats the point of passing in a function when you can just call the function?
Usually, callbacks Javascript are used in Javascript for code that you want to run in the future. The simplest example is setTimeout: if you call the callback now then the code runs immedieately instead of after 500 ms.
//prints with a delay
console.log("Hello");
setTimeout(function(){
console.log("Bye");
}, 500);
//no delay this time
console.log("Hello");
console.log("Bye");
Of course, it would be really neat if we could write something along the lines of
//fake Javascript:
console.log("Hello");
wait(500);
console.log("Bye");
But sadly Javascript doesnt let you do that. Javascript is strictly single-threaded so the only way to code the wait function would be to pause the execution of any scripts in the page for 500 ms, which would "freeze" things in an unresponsive state. Because of this, operations that take a long time to complete, like timeouts or AJAX requests usually use callbacks to signal when they are done instead of blocking execution and then returning when done.
By the way, when passing callbacks you should only pass the function name. If you add the parenthesis you are instead calling the function and passing its return value instead:
//When you write
foo(10, mycallback());
//You are actually doing
var res = mycallback();
foo(10, res);
//which will run things in the wrong order
Your code is not correct as Felix Kling already pointed out. Besides this, passing a function instead of calling one directly allows you to insert different behavior, your code is more decoupled and flexible. Here an example:
function sayBye(){
alert("Bye!");
}
function saySeeYou(){
alert("See you!");
}
function sayHello(name,myfunc){
alert("Hello");
if (myfunc) {
myfunc();
}
}
sayHello("Max",saySeeYou);
// I'm inserting a different behavior. Now instead of displayng "See you!"
// will show "Bye!".
sayHello("Max",sayBye);
You are doing it wrong, you should do like bellow
Don't call the function just pass the function as callback
use this
sayHello("Max",saySeeYou); //here the second parameter is function
instead of
sayHello("Max",saySeeYou());//This will put the result of saySeeYou as second parameter
in say hello call the functiom
function sayHello(name,myfunc){
console.log("Hello");
myfunc();
}

Expected Token Error for setTimeout

What am I doing wrong here?
<script>setTimeout($("#fsForm1585007").hide();,8000);</script>
Sorry, I'm very new to JS. Thanks!
The error is due to the semicolon, however, this still wont' do what you want. You are hiding the element immediately and then passing the result of hide into setTimeout. YOu want to instead do this:
setTimeout(function(){
$("#fsForm1585007").hide();
},8000);
In this way, you are passing a function, which, when invoked will hide your element.
setTimeout correct syntax is:
setTimeout(function ()
{
alert("hello!");
}, 1000);
The "function ()" is a anonymous function parameter of setTimeout(), and "1000" represent the milliseconds to execute the inner code.
Anyway, you can call setTimeout by a function name as string, like this:
setTimeout("YourNewFunction", 1000);
function YourNewFunction()
{
alert("hello!");
}
Important to say your code are using jQuery, you need import jquery script on your page.
Download or use from CDN.

timedout function in jquery

What is the timed out function in jquery ?
setTimeout("searchClusterAction(action)",3000);
function searchClusterAction(action)
{
var url = action
$(location).attr('href',url);
}
on using timedout I'm getting error on line2
var action = "/search/perform/1584/xyz/["1","2","3","4,5,6"]/json
setTimeout('searchClusterAction('+action+')',3000);
The setTimeout() function allows JavaScript to make a note to run the given function X milliseconds in the future. (By the way, you should pass functions, not strings to setTimeout(), no matter what w3Schools says)
One caveat: Don't call the function in the setTimeout() call like so:
setTimeout(foo(),1000);
as it will run foo() and then pass the result of foo to setTimeout(). Simply:
setTimeout(function(){ foo(); },1000);
Using setTimeout() for large values
jQuery doesn't have a special timeout function, the native one works perfectly and is easy to use.
var timeout = setTimeout(function(){
$('.example').fadeOut();
},400);

set time out not working with function

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

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

Categories