Home > Web Front-end > JS Tutorial > body text

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

Mary-Kate Olsen
Release: 2024-10-20 07:37:29
Original
962 people have browsed it

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);
Copy after login

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);
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!