Home  >  Article  >  Web Front-end  >  Are There Exceptions to the Deprecation of String Parameters in setTimeout?

Are There Exceptions to the Deprecation of String Parameters in setTimeout?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-20 07:37:29966browse

Are There Exceptions to the Deprecation of String Parameters in setTimeout?

The Deprecation of Passing Strings to setTimeout: Is There Ever an Exception?

Despite the widespread consensus that passing strings to setTimeout is undesirable, there may be instances where this practice is entertained. This begs the question: are there legitimate reasons for violating this convention?

The conventional reason for rejecting string parameters is that they execute in the global scope, incurring performance challenges and potential security vulnerabilities. Modern syntax eschews this approach in favor of passing functions as arguments to setTimeout:

setTimeout(function() {
    doSomething(someVar);
}, 10000);

Consider the scenario where a function or variable exists globally but is overridden locally. The developer may contemplate using the deprecated syntax to access the global instance:

setTimeout('doSomething(someVar)', 10000);

However, accessing global variables through the window object (e.g., window.globalVar) eliminates the need for this exception.

The allowance of string parameters in setTimeout and setInterval is likely due to their historical precedence. Initially, these functions only accepted strings containing code to execute. The introduction of Function objects as valid arguments came later. Disallowing string parameters retroactively would break existing code.

The above is the detailed content of Are There Exceptions to the Deprecation of String Parameters in setTimeout?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn