惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Last Week in AI
Last Week in AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园_首页
雷峰网
雷峰网
IT之家
IT之家
I
InfoQ
酷 壳 – CoolShell
酷 壳 – CoolShell
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
B
Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 【当耐特】
大猫的无限游戏
大猫的无限游戏
博客园 - 聂微东
Hugging Face - Blog
Hugging Face - Blog
A
About on SuperTechFans
月光博客
月光博客
P
Proofpoint News Feed
博客园 - 三生石上(FineUI控件)
J
Java Code Geeks
G
Google Developers Blog
小众软件
小众软件
宝玉的分享
宝玉的分享
Jina AI
Jina AI
V
Visual Studio Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Simplify setTimeout
Samuel Rouse · 2026-05-18 · via DEV Community

Hidden in plain sight is a functional programming interface you may have never used, and understanding it can change the way you code. It also fixes a classic JavaScript "gotcha"!

setTimeout is a staple of example code. When simulating asynchronous actions for demos, setTimeout is the go-to function. But there's always a bit of anonymous function boilerplate in the examples.

Classic setTimeout

You've probably seen examples like these many times:

const aPromise = new Promise((resolve, reject) => {
  setTimeout(() => resolve('a value'), 1000);
});

const bPromise = new Promise(function(resolve, reject) {
  setTimeout(function() {
    reject(new Error('oops'));
  }, 1000);
});

Enter fullscreen mode Exit fullscreen mode

In each of these cases we're passing an anonymous function to setTimeout and the function doesn't accept any arguments. Because, where would those arguments come from?!

As it turns out, they come from setTimeout itself! Everything after the first two parameters are passed as arguments to the callback. This lets us lose the anonymous functions and pass parameters that the callback will consume rather than relying on the closure to retain scope.

Functional setTimeout

By passing the parameters to setTimeout, we can eliminate the anonymous function wrapping our action.

const aPromise = new Promise((resolve, reject) => {
  setTimeout(resolve, 1000, 'a value');
});

const bPromise = new Promise(function(resolve, reject) {
  setTimeout(reject, 1000, new Error('oops'));
});

Enter fullscreen mode Exit fullscreen mode

This simplifies writing the code and teaches you to think about the way you use and call functions a bit differently. A lot of coding examples contain anonymous functions like this. Timers, event handlers, promise chains, and regular callbacks.

Functional Thinking

Once you recognize the values are passed in from outside the anonymous function and don't exist because of it, you start thinking more like functional programming.


// Common example promise chain
somePromise
  .then((data) => transformData(data))
  .then((newData) => displayData(newData))
  .catch((err) => console.error(err));

// This works the same way without anonymous functions.
somePromise
  .then(transformData)
  .then(displayData)
  .catch(console.error);

Enter fullscreen mode Exit fullscreen mode

Just as .then and .catch will call an anonymous function, passing it a single argument, it will call the named function and pass it the same argument. The anonymous function doesn't create anything; it lets us "see" the value for ourselves and give them a name temporarily.

Fixing JavaScript Gotchas

Even if you don't see ECMAScript 5 code as often these days you are likely still aware of the lack of block scoping that var has, compared to the ES2015 let and const. This is the classic "gotcha" code example:

// logs 10 ten times
for (var i = 0;i < 10;i += 1) {
  setTimeout(() => console.log(i), 10);
}

// logs 0-9
for (let i = 0;i < 10;i += 1) {
  setTimeout(() => console.log(i), 10);
}

Enter fullscreen mode Exit fullscreen mode

In ES5, we used to "get around" this limitation by passing the variable to a function immediately to ensure the value in the current loop value was consumed instead of the ending value.

function timeoutLogger(value) {
  setTimeout(console.log(value), 10);
}

// logs 0-9
for (var i = 0;i < 10;i += 1) {
  // Current value of i is passed to the function immediately.
  timeoutLogger(i);
}

Enter fullscreen mode Exit fullscreen mode

setTimeout supported these callback parameters for more than a decade before ES2015 was introduced, though. Though our callback runs later, we can call setTimeout immediately and the value is "stored" internally, even without the block-scoped let.

// logs 0-9
for (var i = 0;i < 10;i += 1) {
  setTimeout(console.log, 10, i);
}

Enter fullscreen mode Exit fullscreen mode

No need for extra layers or tricks.

Scopes & Closures

Understanding this option can also help clarify how scopes and closures work.

The var "gotcha" is a problem because of misunderstanding scope and closures. The for loop with var contains a single scope "outside" the loop instances, and because the variable i isn't passed into the anonymous function callback to setTimeout; it closes over the scope of the entire loop and accesses it once it's already finished.

The let solution changes the scope to solve for a developer's incorrect expectation. Each loop gets a separate scope to make sure that asynchronous scope consumers have access to the per-loop value. This isn't really better, just different. The simple example shows it as solving a problem, but it's really a problem of the coding style rather than the language.

Passing the value as a parameter "uses" the value immediately. We don't depend on a closure or a scope, we synchronously execute setTimeout and it consumes the value during the loop where it is called. The same thing happened with the timeoutLogger example. We consumed the value of i synchronously. This created a new scope where it was available to the anonymous function in setTimeout. This is how most asynchronous actions in loops handled the scope prior to ES2015. I can't say I recall any instances of the argument style in "the old days".

Conclusion

This often-overlooked capability of setTimeout both eliminates a common "gotcha" in coding examples and tests, and can help you understand the difference of passed values and scopes/closures better, as well as get you thinking about using functions as arguments directly rather than wrapping them with anonymous functions to help you visualize the inputs and outputs.

If you see this differently, I'd love to hear how you think about it!