Question: I have read the relevant pages on w3schools and other similar questions here but cannot seem to understand what's wrong about the following bit :

```
var myfunc03 = function (i) {
  document.getElementById('d01').innerHTML += 100-i+"<br>";
};

var myFunc01 = function() {
  i=0;
  while (i<100) {
    setTimeout(myfunc03(i), 1000)
    i++;
  }
};

```

when `myFunc01();` is run.

There's no pause whatsoever and all possible values for i is listed at once.

Is there a logical mistake here?

Answer: 
The `while` loop will not wait for **[`setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout)** to complete. You need to set different time delay for each to execute them with different times and use closure for holding the value of `i`. Also in your case, function will be executed initially and return value is setting as argument in **[`setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout)**, so either you need to call the function inside an anonymous function or set the function directly.

```js
var myFunc01 = function() {
  var i = 0;
  while (i < 100) {
    (function(i) {
      setTimeout(function() {
        document.getElementById('d01').innerHTML += 100 - i + "<br>";
      }, 1000 * i)
    })(i++)
  }
};

myFunc01();
```

```html
<span id="d01"></span>
```

---

Although **[`setInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval)** can be used here

```js
var myFunc01 = function() {
  var i = 0;
  // store the interval id to clear in future
  var intr = setInterval(function() {
    document.getElementById('d01').innerHTML += 100 - i + "<br>";
    // clear the interval if `i` reached 100
    if (++i == 100) clearInterval(intr);
  }, 1000)

}

myFunc01();
```

```html
<span id="d01"></span>
```
You can do it **more simply** with **recursion**:

```
var i = 0;
function f1() { ... };   
function f() {
    f1();
    i += 1;
    setTimeout(function() {
        if(i < 100) {
            f();
        }
    }, 1000);
}
f();

```

### Example

```js
var i = 0;

var myfunc03 = function(i) {
  document.getElementById('d01').innerHTML += 100 - i + "<br>";
};

var myFunc01 = function() {
  myfunc03(i);
  i += 1;
  setTimeout(function() {
    if (i < 100) {
      myFunc01();
    }
  }, 1000);
}

myFunc01();
```

```html
<div id="d01"></div>
```

---

A reusable function
-------------------

```js
function say(sentence) {
  console.log(sentence);
}

function sayHello() {
  say("Hello!");
}

var fn = sayHello;
var count = 10;
var ms = 1000;

function repeat(fn, count, ms) {
  var i = 0;

  function f() {
    fn();
    i += 1;
    setTimeout(function() {
      if (i < count) {
        f();
      }
    }, ms);
  }

  f();
}

repeat(fn, count, ms);
```