John White
John White

Reputation: 161

What is wrong with my JS setTimeout() parameter

In the following snippet, I can't see why the commented-out line doesn't work, while the line after does work:

function clicked()  {
    var t1 = setInterval(print, 100);
//  setTimeout(clearInterval(t1), 16000);
    setTimeout(function(){clearInterval(t1)}, 1600);

Upvotes: 0

Views: 65

Answers (3)

Lovro
Lovro

Reputation: 185

Another way would be:

setTimeout(clearInterval.bind(null,t1), 1600);

Upvotes: 0

Or Yaniv
Or Yaniv

Reputation: 571

that is because setTimeout's first parameter is a supposed to be a function. that's why you can give it things like "print" which i assume is a function in your context, or "function(){clearInterval(t1)}" which is an anonymous function that uses clearInterval.

however, the value of "clearInterval(t1)" which is calling clearInterval on t1, is the return value of clearInterval, which probably isn't a function. that is all.

Upvotes: 1

Quentin
Quentin

Reputation: 943214

The first argument of setTimeout should be a function.

clearInterval is a function.

clearInterval(t1) is the return value you get when you immediately call the function.

Upvotes: 4

Related Questions