DigitalDesignDj DigitalDesignDj - 2 months ago 11
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 () {
console.log('beep')
setTimeout( test, 100 );
}();


Anybody know why this only runs once and not forever?

Answer

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

You can declare it as a named function expression:

(function test() {
  console.log('beep')
  setTimeout(test, 100);
})();

Or postpone calling the function until after the assignment:

var test = function() {
  console.log('beep')
  setTimeout(test, 100);
};
test();

Comments