Interview Question 1

by Arnaud Buchholz

HTML

<h1>
Interview Question 1
</h1>
<blockquote>
  The <code>click</code> function below is executed when clicking <button>
  click me!</button>.
  <pre><code>function click () {
  output('Button clicked')
  for (var i = 0; i &lt; 10; ++i) {
    setTimeout(function () {
      <span class="output">output</span>(i)
    }, 1000)
  }
}</code></pre>
  The <code><span class="output">output</span></code> function generates a trace that begins with a timestamp (<i>refer to the example below</i>).
  <ul>
    <li>Your task is to <b>anticipate</b> the output of the function when the button is clicked: please specify each timestamp and its corresponding value.</li>
  </ul>
  Feel free to express your thoughts openly and elaborate on your reasoning.
</blockquote>
<script>
const el = document.createElement.bind(document)
const tx = document.createTextNode.bind(document)
function output (msg) {
	const line = el('div')
  const timestamp = line.appendChild(el('span'))
  timestamp.className = 'timestamp'
  const now = new Date()
  const z = n => n.toString().padStart(2, '0')
  timestamp.appendChild(tx(`${z(now.getHours())}:${z(now.getMinutes())}:${z(now.getSeconds())}`))
  const message = line.appendChild(el('span'))
  message.className = 'message'
  message.appendChild(tx(msg))
  document.body.appendChild(line)
}

const button = document.querySelector('button')
window.addEventListener('load', () => button.addEventListener('click', click))
output("Example of output")
</script>

CSS

.timestamp {
  color: gray;
  margin-right: 4px;
}

blockquote {
  padding: 0.5rem;
  margin: 1rem;
  background-color: lightgray;
}

li {
  padding-bottom: 1rem;
}

span.output {
  color: purple;
}

JavaScript

function click () {
  output('Button clicked')
	for (var i = 0; i < 10; ++i) {
	  setTimeout(function () {
      output(i)
	  }, 1000)
	}
}