• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

My Monkey Do

A Log of Coding Solutions

  • Home
  • Web Hosts
  • Tools
  • About

Passing parameters to setTimeout in a loop

July 12, 2012 by Webhead

Problem

I know to pass a parameter to a setTimeout function you would use javascript’s “closure” to get it to work:

setTimeout(function(){alert(someParameter)}, 1000);

However if you are setting someParameter in a loop, setTimeout will always alert the last value set to someParameter.

 

Solution

The solution is to set a scope around setTimeout like so:

var strings = [ "hello", "world" ]; var delay = 1000; for(var i=0;i<strings.length;i++) {     (function(s){         setTimeout( function(){alert(s);}, delay);     })(strings[i]);     delay += 1000; }

source: http://stackoverflow.com/questions/6425062/passing-functions-to-settimeout-in-a-loop-always-the-last-value

 

Filed Under: Coding Tagged With: javascript

Primary Sidebar

Topics

apache apple block editor chrome cms css debug eCommerce embed firebug firefox git gmail goDaddy google hosting htaccess html html 5 IE crap image iPad iPhone javascript jquery linux localization mac os x ms sql mysql open source optimize php php 5.3 responsive rest api seo svg tinymce woocommerce wordpress wpengine xss yii youtube




Categories

  • Coding
  • Off the Shelf
  • Plugins
  • Random Thoughts
  • Server Stuff
  • Tools