Seena Khoee
Seena Khoee

Reputation: 29

setTimeout JS keeps on running

I'm confused on the way the method setTimeout is working with JS. why is it when I call the firstFunction the setTimeout only runs once AND when I call the secondFunction it keeps on calling the function.

I would expect consistency. Either the firstFunction, setTimeout would continue calling the log function OR in the secondFunction the setTimeout will only call the secondFunction once and finish.

var firstFunction = function(){
    var log = console.log('hello')
    setTimeout(log, 2000);
}

firstFunction();

var secondFunction = function(str){
    console.log(str)
    setTimeout("secondFunction('test')", 2000);
}

secondFunction('test');

Upvotes: 0

Views: 1582

Answers (1)

GantTheWanderer
GantTheWanderer

Reputation: 1292

The first snippet is incorrect. console.log('hello') runs immediately and the timeout doesn't trigger anything because in your example log is undefined.

Here is what a working example would look like:

var firstFunction = function(){
    var log = function() { console.log('hello'); };
    setTimeout(log, 2000);
}

firstFunction();

The second snippet loops forever because you are telling it to do the following:

1) Run the statement secondFunction('test')

2) Log the parameter and set a time out for 2 seconds.

3) once the timeout ends, run the statement secondFunction('test')

4) Log the parameter and set a time out for 2 seconds.

5) once the timeout ends, run the statement secondFunction('test')

...

n) Repeats forever

var secondFunction = function(str){
    console.log(str)
    setTimeout("secondFunction('test')", 2000);
}

secondFunction('test');

Notice that in the first example, the timeout doesnt call the firstFunction again, it calls a function called log, and log does not create another timeout callback, so it only runs once.

**Edit - How to call it not using a string as the function parameter? **

Also its probably not preferable to call this with a string. Call it using a reference to a function. This is demonstrated in the first example where the function log is declared and passed into setTimeout. But you could also do it this way:

var thirdFunction = function(){
    setTimeout(function() { console.log('Hello World'); }, 1000);
}

thirdFunction();

Upvotes: 3

Related Questions