settimeout-iif.js
✓ Published0🌍 Public
Aalessioalex
Last edited Nov 22, 2014
Created on Nov 22, 2014
This example demonstrates how JavaScript’s closure scope preserves loop variable values inside asynchronous callbacks. The code defines a `tellMeLater` function that iterates ten times, each iteration wrapping a `setTimeout` call in an immediately-invoked function expression (IIFE). By passing `i` as an argument to the IIFE, each timeout callback logs its own unique index (0 through 9) after a 100-millisecond delay, avoiding the classic loop-variable capture problem. The example uses no external libraries, relying solely on native JavaScript `setTimeout` and `console.log` to show the expected sequential output.
AI-generated description