Is It a jQuery Bug? - J Query

Problem
You’re calling some jQuery code to show a hidden element and set its HTML content
after a time delay using setTimeout():

The .show() call works, but the .html(text) call fails. The Firebug console reports that the text variable is undefined. The same jQuery code works when you don’t call it from setTimeout(). Is there a problem using jQuery with setTimeout()?

Solution

One way to find out whether jQuery is the source of a problem is to replace your jQuery code with other JavaScript code that does n’t use jQuery. In this example, we can replace the jQuery code with a simple alert():

When we try this version of the code, the same problem occurs: there is no alert, and Firebug again reports that text is undefined.
This doesn’t identify the problem, but it narrows it down a lot. It clearly isn’t jQuery (unless the mere presence of the jQuery library is interfering with your page, but you can rule that out by running the code in a simple test page that doesn’t include jQuery).So, it must be something wrong with this code itself, most likely to do with the way we’re using setTimeout().
Indeed, the problem here is that when a string argument is passed to setTimeout(), it is executed in the global scope, i.e., as if the code were located outside of any function.The easiest way to fix it is to use a local function for the callback instead of a text string:

Unlike code in a string, a nested function has full access to the outer function’s variables and parameters. So, this code will alert the text as expected.
And finally, here is a corrected version of the original jQuery code:

Discussion
When debugging, if you aren’t sure what is causing a problem, finding out where the problemisn’t can help you track it down. The purpose of this recipe isn’t to help you troubleshootsetTimeout() problems—after all, this is a jQuery book, not a general JavaScript book—but to help you focus your debugging efforts by quickly ruling out (or confirming!) jQuery as the source of the problem.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics