Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout callback argument

Tags:

Let's consider this piece of JavaScript:

function Person(name) {
    this.name = name;
}

Person.prototype.showName = function() {
    alert(this.name);
}


var mike = new Person("mike");
//mike.showName();  

window.name = "window"; 

I don't understand the difference between the behavior of

setTimeout(mike.showName(), 5000);

and

setTimeout(function(){
    mike.showName();
}, 5000);

Why is the behavior different? It really confuses me. Thanks.

like image 887
jsnewman Avatar asked Apr 02 '11 00:04

jsnewman


People also ask

How do you pass arguments in setTimeout?

You can pass the parameter to the setTimeout callback function as: setTimeout(function, milliseconds, param1, param2, ...) eg. Yeah!

Does setTimeout use callback?

Introduction to JavaScript setTimeout()The setTimeout() sets a timer and executes a callback function after the timer expires. In this syntax: cb is a callback function to be executed after the timer expires. delay is the time in milliseconds that the timer should wait before executing the callback function.

How many arguments will setTimeout take?

Bookmark this question. Show activity on this post. This SO answer makes a call to setTimeout with four arguments.


1 Answers

Your question really has nothing at all to do with setTimeout. You simply need to understand the difference between a function call and a reference to a function.

Consider these four assignments:

var one = function() { mike.showName(); };
var two = mike.showName;
var three = mike.showName();
var four = (function() { mike.showName(); })();

The first two assign a reference to a function to their respective variables. The last two, however, call functions (that's what the parens are for) and assign their return values to the vars on the left-hand side.

How this relates to setTimeout:

The setTimeout function expects as its first argument a reference to a function, so either one or two above would be correct, but three and four would not. However, it is important to note that it is not, strictly speaking, a mistake to pass the return value of a function to setTimeout, although you'll frequently see that said.

This is perfectly fine, for example:

function makeTimeoutFunc(param) {
    return function() {
        // does something with param
    }
}

setTimeout(makeTimeoutFunc(), 5000);

It has nothing to do with how setTimeout receives a function as its argument, but that it does.

like image 95
Wayne Avatar answered Oct 22 '22 08:10

Wayne