Home > Web Front-end > JS Tutorial > 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
Release: 2024-11-15 17:04:02
Original
685 people have browsed it

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

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

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

    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!

source:php.cn
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