Why Is the Method Executed Immediately When I Use Settimeout

Why is the method executed immediately when I use setTimeout?

You're calling the function immediately and scheduling its return value.

Use:

setTimeout(testFunction, 2000);
^

Notice: no parens.

setTimeout executes immediately instead of time passed in the function call

First parameter of setTimeout() is the function, but in your code, you are executing the function. Make it as a function using arrow function.

function formatName(fname,lname){
let fullName = fname+lname;
console.log(fullName);
}
setTimeout(() => formatName('Jon','Harris'),5000);

Why is setTimeout executing immediately?

because you're actually calling the timeup(tc,chosen) function inside the setTimeout function.

try:

setTimeout(function(){
timeup(tc,chosen);
}, 10000);

setTimeout -- callback executed immediately?

Several problems.

This invokes hide_info right away. Parenthesis invoke a function-object! (or are used for applying precedence to expressions).

That is,

this.id = setTimeout(this.hide_info(), 7000);

Is [mostly] equivalent to:

var temp = this.hide_info()       // call function ... uh, what?
this.id = setTimeout(temp, 7000) // temp is "return" value ("undefined" here)

Oops! That's not right :) So take away the parenthesis. This will pass the function-object itself to the setTimeout. (Yes, functions are just objects in JavaScript. The expression this.hide_info is first evaluated to a function-object and, if there is a (...) after, it will invoke said function-object.)

this.id = setTimeout(this.hide_info, 7000)

However, it is still not correct because this inside the timeout function (hide_info) will be wrong! But this can be fixed with using a closure. (There are many great SO answers on the topic, feel free to search!)

var self = this
this.id = setTimeout(function () {
// now in hide_info "this" will be "self", which was "this" ... outside :)
self.hide_info()
}, 7000)

(Or use Function.bind from ECMAScript ed5 or a library.)

Additionally, this.id is not the same as this.timeoutID, and is suspect for "correctness".

Keep it simple. It's okay to pass undefined/0 to clearTimeout: it'll silently ignore you.

cancel : function () {
clearTimeout(this.id) // but id is a horrid overloaded name :)
this.id = undefined
}

Happy coding.

setTimeout in javascript executing timeout code right away and not waiting

setTimeout accepts a function as the first argument, unless reload() return a function to be run, you probably wanted

setTimeout(reload, 30000);


Related Topics



Leave a reply



Submit