Home  >  Article  >  Web Front-end  >  Why is my `setTimeout` function being executed immediately instead of after the delay?

Why is my `setTimeout` function being executed immediately instead of after the delay?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-15 17:04:02599browse

Why is my `setTimeout` function being executed immediately instead of after the delay?

Why Immediate Execution of setTimeout-Scheduled Function Occurs

In this scenario, where a function is intended to be executed with a delay using setTimeout but is instead executed immediately, the issue lies in how the function is passed to setTimeout.

To resolve this issue, there are three approaches to ensure it executes with the desired delay:

  1. Pass Arguments Individually:

    setTimeout(doRequest, proxytimeout, url, proxys[proxy]);

    This form passes the function first, followed by the timeout and the function's arguments.

  2. Use a Literal String:

    setTimeout('doRequest('+url+','+proxys[proxy]+')', proxytimeout);

    Here, a literal string is provided, which will be evaluated at execution time.

  3. Anonymous Function Closure:

    (function(u, p, t) {
        setTimeout(function() { doRequest(u, p); }, t);
    })(url, proxys[proxy], proxytimeout);

    This approach involves an anonymous function that calls the intended function. The closure ensures that the values used in the function remain consistent throughout the loop.

By adopting any of these methods, you can effectively schedule the execution of the doRequest function with the specified delay.

The above is the detailed content of Why is my `setTimeout` function being executed immediately instead of after the delay?. 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