DigitalDesignDj DigitalDesignDj - 1 year ago 68
Javascript Question

Why does this function only run once?

I really think this should run every 100ms, but it only beeps once.

I know about setInterval, but this confuses me.

var test = function () {
setTimeout( test, 100 );

Anybody know why this only runs once and not forever?

Answer Source

The anonymous function is being executed before it's assigned to test.

You can declare it as a named function expression:

(function test() {
  setTimeout(test, 100);

Or postpone calling the function until after the assignment:

var test = function() {
  setTimeout(test, 100);