By BoLOBOSE payday loan

JavaScript: setTimeout Firing Immediately

Today at work I needed to do some Ajax calls to update some information in the database and pull the most recent results for the administration side of the project. I was stumped for about 10 minutes while trying to figure out why my button would not change back to its original state after displaying “updated.” It turns out that when you call a function using ‘setTimeout’ and you do not wrap the function in quotation marks, the function will be triggered immediately.

1
2
3
4
5
//function is triggered immediately.
setTimeout(updateRecord(), 500);
 
//function is triggered after the set time.
setTimeout("updateRecord()", 500);

This immediate triggering makes sense when you think about how the triggering within the parameters operates but it got me all the same.

Related posts:

  1. Javascript Hoirzontal Menu
  2. Javascript Canvas: Basic Game Logic and Movement
Caleb Jonasson

About: Caleb Jonasson

I am a web application developer currently spending my days coding at work, completing contracts and running around with my Nikon. This is my primary place for updates and everything code, technology and database related.
  • http://twitter.com/monchote Ramón Argüello

    The problem is that setTimeout receives a function as the first parameter and by including () after updateRecord you are executing it and passing its result to setTimeout. The right way of doing it would be:

    setTimeout(updateRecord, 500);

    I don’t even know why passing “updateRecord()” as a String even works, to be honest, but it doesn’t look very safe.