-1

Usually you assign a setTimeout to a variable, if you want to cancel the timeout later.

I've wrote a simple setTimeout in console, and to my surprise, the console returned a number. What is the meaning of this number?

<< setTimeout(function(data){console.log(data)},2000,"data passed as arg");
>> 114
sanjihan
  • 5,592
  • 11
  • 54
  • 119
  • 4
    [Here ...](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout), I'm just wondering ... "_This question does not show any research effort ..._", or the old good "RTFM". – Teemu Jan 19 '18 at 21:55
  • my bad, google was vague, but never explicitly searched the docs – sanjihan Jan 19 '18 at 22:01
  • Well, I didn't vote down, the question is clear = ). – Teemu Jan 19 '18 at 22:02

3 Answers3

5

It's a timer identifier, that allows you to cancel it later

const a = setTimeout (console.log, 1000, 'hello A')
const b = setTimeout (console.log, 1000, 'hello B')
clearTimeout (a)
// you won't see 'hello A', because it was canceled
// you will only see 'hello B'

It works for setInterval and clearInterval too

const t = setInterval (console.log, 1000, 'hello world')
setTimeout (clearInterval, 5000, t)
// outputs 'hello world' once per second
// 5 seconds later, the interval timer is canceled
Mulan
  • 129,518
  • 31
  • 228
  • 259
  • The second example works, but to quote the [docs](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout): "*`clearTimeout()` and `clearInterval()` can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code.*" – Herohtar Jan 19 '18 at 22:31
  • 1
    @Herohtar wups, I did intend to use the proper one. Thanks for catching that. – Mulan Jan 19 '18 at 22:32
4

It's an identifier for the timer. You can pass it to clearTimeout() to cancel the operation.

Pointy
  • 405,095
  • 59
  • 585
  • 614
2

See the docs:

The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout(); this value can be passed to clearTimeout() to cancel the timeout.

pushkin
  • 9,575
  • 15
  • 51
  • 95