Condition-Based Waiting
Replace arbitrary timeouts with condition polling for reliable async tests
Skill by shrivatsas
Install
Works with Claude Code, Claude apps, Codex, Cursor, Gemini CLI, GitHub Copilot, VS Code, OpenCode, Goose, Windsurf. Read the repository before you give any tool access to your data.
npx agentmarket install skill/shrivatsas-condition-based-waiting
Asks which of your tools to add it to (Claude Code, Codex, Cursor, VS Code, Windsurf, Gemini CLI, Claude Desktop) and shows the change first. See https://agentmart.dev/cli.
Get the weekly diff
The weekly diff: one email a week with new agent tools, notable updates and grade changes, plus security alerts for tools you follow. Double opt-in, one-click unsubscribe.
About
Reviews
Write a reviewNo reviews yet. Installed it? Reviews come from verified installers only. How reviews work
Permissions
What this skill can do and what it asks for, from its SKILL.md. Checked Oct 25, 2026.
- Tools
- No tools found
- Secrets
- None asked for
- Install scripts
- None found
- Runs as
- Node.js package
Network hosts it talks to 1
codeload.github.com· found in install command
Files it touches
~/.claude/skills/condition-based-waiting
What's inside
- Skill name
Condition-Based Waiting- Description
- Replace arbitrary timeouts with condition polling for reliable async tests
- License
- MIT
- Instructions
- 117 lines in SKILL.md · view on GitHub
Before installing
- Ships executable scripts
Agent Skills spec issues
- name: only lowercase letters, digits and single hyphens allowed
- name: "Condition-Based Waiting" does not match folder "condition-based-waiting"
Files (2)
- SKILL.md
- example.ts
SKILL.md (first lines)
# Condition-Based Waiting
## Overview
Flaky tests often guess at timing with arbitrary delays. This creates race conditions where tests pass on fast machines but fail under load or in CI.
**Core principle:** Wait for the actual condition you care about, not a guess about how long it takes.
## When to Use
```dot
digraph when_to_use {
"Test uses setTimeout/sleep?" [shape=diamond];
"Testing timing behavior?" [shape=diamond];
"Document WHY timeout needed" [shape=box];
"Use condition-based waiting" [shape=box];
"Test uses setTimeout/sleep?" -> "Testing timing behavior?" [label="yes"];
"Testing timing behavior?" -> "Document WHY timeout needed" [label="yes"];
"Testing timing behavior?" -> "Use condition-based waiting" [label="no"];
}
```
**Use when:**
- Tests have arbitrary delays (`setTimeout`, `sleep`, `time.sleep()`)
- Tests are flaky (pass sometimes, fail under load)
- Tests timeout when run in parallel
- Waiting for async operations to complete
**Don't use when:**
- Testing actual timing behavior (debounce, throttle intervals)
- Always document WHY if using arbitrary timeout
## Core Pattern
```typescript
// ❌ BEFORE: Guessing at timing
await new Promise(r => setTimeout(r, 50));
const result = getResult();
expect(result).toBeDefined();
// ✅ AFTER: Waiting for condition
await waitFor(() => getResult() !== undefined);
const result = getResult();
expect(result).toBeDefined();
```
## Quick Patterns
| Scenario | Pattern |
|----------|---------|
| Wait for event | `waitFor(() => events.find(e => e.type === 'DONE'))` |
| Wait for state | `waitFor(() => machine.state === 'ready')` |
| Wait for count | `waitFor(() => items.length >= 5)` |
| Wait for file | `waitFor(() => fs.existsSync(path))` |
| Complex condition | `waitFor(() => obj.ready && obj.value > 10)` |
## Implementation
Generic polling function:
```typescript
async function waitFor<T>(
condition: () => T | undefined | null | false,
description: string,
timeoutMs = 5000
): Promise<T> {
const startTime = Date.now();
while (true) {
const result = condition();
if (result) return result;
if (Date.now() - startTime > timeoutMs) {
throw new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`);
}
await new Promise(r => setTimeout(r, 10)); // Poll every 10ms
}
}
```
See @example.ts for complete implementation with domain-specific helpers (`waitForEvent`, `waitForEventCount`, `waitForEventMatch`) from actual debugging session.
## Common Mistakes
**❌ Polling too fast:** `setTimeout(check, 1)` - wastes CPU
**✅ Fix:** Poll every 10ms
**❌ No timeout:** Loop forever if condition never met
**✅ Fix:** Always include timeout with clear error
**❌ Stale data:** Cache state before loop
**✅ Fix:** Call getter inside loop for fresh data
## When Arbitrary Timeout IS Correct
```typescript
// Tool ticks every 100ms - need 2 ticks to verify partial output
await waitForEvent(manager, 'TOOL_STARTED'); // First: wait for condition
await new Promise(r => setTimeout(r, 200)); // Then: wait for timed behavior
// 200ms = 2 ticks at 100ms intervals - documented and justified
```
**Requirements:**
1. First wait for triggering condition
2. Based on known timing (not guessing)
3. Comment explaining WHY
## Real-World Impact
From debugging session (2025-10-03):
- Fixed 15 flaky tests across 3 files
- Pass rate: 60% → 100%
- Execution time: 40% faster
- No more race conditionsFrom shrivatsas/dev-setup, MIT.
More from shrivatsas/dev-setup
- 0.512score
architecture-docs
shrivatsas
Generate or update architecture documentation from repositories, product docs, infrastructure files, and code.
SkillCFreshness: C★ 2Claude Code +9 - 0.512score
domain-driven-design
shrivatsas
DDD planning and review workflow for greenfield systems and brownfield codebases.
SkillCFreshness: C★ 2Claude Code +9 - 0.504score
codex
shrivatsas
Use OpenAI Codex CLI for complex debugging, code analysis, or when stuck on difficult problems.
SkillCFreshness: C★ 2Claude Code +9 - 0.503score
sync-dev-skills
shrivatsas
Copy the skills collection from /Users/shrivatsa/Documents/dev-setup/skills into the current repository, another repository, or an explicit skills directory.
SkillCFreshness: C★ 2Claude Code +9 - 0.493score
Gardening Skills Wiki
shrivatsas
Maintain skills wiki health - check links, naming, cross-references, and coverage
SkillCFreshness: C★ 2Claude Code +9 - 0.477score
grill-me
shrivatsas
Interview the user relentlessly about a plan or design until reaching shared understanding, resolving each branch of the decision tree.
SkillCFreshness: C★ 2Claude Code +9
Signals
- Stars
- 2
- Forks
- 0
- Open issues
- 0
- Last commit (this folder)
- May 25, 2026 (5 months ago)
From GitHub (fetched Oct 24, 2026).
Details
- License
- MIT
- Repository
- github.com/shrivatsas/dev-setup
- First seen
- Oct 24, 2026
- Last checked
- Oct 24, 2026
- Source
- GitHubgithub-graphql
More from shrivatsas
- 0.512score
architecture-docs
shrivatsas
Generate or update architecture documentation from repositories, product docs, infrastructure files, and code.
SkillCFreshness: C★ 2Claude Code +9 - 0.512score
domain-driven-design
shrivatsas
DDD planning and review workflow for greenfield systems and brownfield codebases.
SkillCFreshness: C★ 2Claude Code +9 - 0.504score
codex
shrivatsas
Use OpenAI Codex CLI for complex debugging, code analysis, or when stuck on difficult problems.
SkillCFreshness: C★ 2Claude Code +9 - 0.503score
sync-dev-skills
shrivatsas
Copy the skills collection from /Users/shrivatsa/Documents/dev-setup/skills into the current repository, another repository, or an explicit skills directory.
SkillCFreshness: C★ 2Claude Code +9 - 0.493score
Gardening Skills Wiki
shrivatsas
Maintain skills wiki health - check links, naming, cross-references, and coverage
SkillCFreshness: C★ 2Claude Code +9 - 0.477score
grill-me
shrivatsas
Interview the user relentlessly about a plan or design until reaching shared understanding, resolving each branch of the decision tree.
SkillCFreshness: C★ 2Claude Code +9
Cite this page
Condition-Based Waiting skill. Agent Mart. https://agentmart.dev/skills/shrivatsas-condition-based-waiting (last updated 2026-10-24)