Home > Web Front-end > JS Tutorial > Why Does My setTimeout Function Execute Immediately?

Why Does My setTimeout Function Execute Immediately?

DDD
Release: 2024-11-11 17:31:03
Original
713 people have browsed it

Why Does My setTimeout Function Execute Immediately?

Unexpected Immediate Function Execution with setTimeout

In an attempt to schedule a function call at specific intervals, the user encounters an issue where the setTimeout function executes the function immediately, despite the specified timeout. The doRequest function should be called at 10-second intervals, but it's being called right away.

The cause of this immediate execution lies in the way the setTimeout function is being called. The following code snippet demonstrates the issue:

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

In this code, the doRequest function is passed as the first argument to setTimeout, but the function is being executed immediately rather than being scheduled.

Solutions:

To resolve this issue and ensure that doRequest is scheduled, there are three alternative ways to use setTimeout:

  1. Pass the Function Name as a String:

    setTimeout('doRequest(' + url + ',' + proxys[proxy] + ')', proxytimeout);
    Copy after login
  2. Use an Anonymous Function:

    (function(u, p, t) {
        setTimeout(function() { doRequest(u, p); }, t);
    })(url, proxys[proxy], proxytimeout);
    Copy after login
  3. Pass the Function Name First, Then the Parameters:

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

The above is the detailed content of Why Does My setTimeout Function Execute Immediately?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template