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

Why Is My `setTimeout` Function Executing Immediately Instead of at a Scheduled Time?

Susan Sarandon
Release: 2024-11-12 13:40:01
Original
727 people have browsed it

Why Is My `setTimeout` Function Executing Immediately Instead of at a Scheduled Time?

Why Isn't My Function Scheduled by setTimeout Executing Immediately?

Your code seeks to test proxy servers using the setTimeout function to call doRequest with 10-second intervals. Strangely, the functions are executing immediately instead of following the intended schedule.

Understanding the Issue

The problem lies in how you're passing the doRequest function to setTimeout. When you specify a function as the first argument, as in setTimeout(doRequest(url, proxys[proxy]), proxytimeout), the function is invoked immediately.

Solutions

To resolve the issue, you have three options:

  1. Pass the arguments as separate parameters:

    setTimeout(doRequest, proxytimeout, url, proxys[proxy]);
    Copy after login
  2. Use a string expression:

    setTimeout('doRequest(' + url + ',' + proxys[proxy] + ')', proxytimeout);
    Copy after login
  3. Define an anonymous function within a closure:

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

The first option is preferred as it's clearer and more explicit. The second option is less desirable due to its "hacky" nature, while the third option can be complex to understand but prevents values from changing within the loop.

The above is the detailed content of Why Is My `setTimeout` Function Executing Immediately Instead of at a Scheduled Time?. 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