Skip to content

Instantly share code, notes, and snippets.

@techhahn
Created February 7, 2018 19:15
Show Gist options
  • Select an option

  • Save techhahn/9240e7367eaa6917e94b9a5ae8cc4cfe to your computer and use it in GitHub Desktop.

Select an option

Save techhahn/9240e7367eaa6917e94b9a5ae8cc4cfe to your computer and use it in GitHub Desktop.
Any way to print proper values without moving setTimeout outside the loop?
//HTML
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
//JS
var list = document.querySelectorAll('li');
var listArr = Array.prototype.slice.call(list);
for(x in listArr) {
setTimeout(function(){
console.log('The number is '+ listArr[x].innerText);
}, 200);
}
// Expected Result
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
// Actual Result
The number is 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment