What does setTimeout return?
I was curious that what does setTimeout return. So I did a quick test:
var thing = setTimeout(function(){},1);
And what surprise me is that it gave me a number. 1351
Each time is different.
So is it really all it returns is a number? So I can actually do this as well?
clearTimeout(1351);
Very confusing...
It's a handle (a unique identifier). When you create a timeout, the JavaScript runtime associates a handle with the timeout you created, and it can identify that timeout by the handle setTimeout()
returns. When you run clearTimeout()
, it will know what timeout you're talking about by looking at the unique handle you pass in.
It can be an Object
, I tested it with node.js
:
var sto = setTimeout(
function(){console.log('ping');},
1000
);
console.log(sto);
The output is:
{ _idleTimeout: 1000,
_idlePrev:
{ '0': [Function: listOnTimeout],
_idleNext: [Circular],
_idlePrev: [Circular],
msecs: 1000 },
_idleNext:
{ '0': [Function: listOnTimeout],
_idleNext: [Circular],
_idlePrev: [Circular],
msecs: 1000 },
_idleStart: 2413359232,
_onTimeout: [Function],
_repeat: false,
domain:
{ domain: null,
_events: { error: [Function] },
_maxListeners: undefined,
members: [] } }
You can think of it as a timerID
, which uniquely identify a timer, so that you can reset by clearTimeout(timerID)
it's a task ID (I prefer to think it's a task_ID rather than a Timeout_ID that confuses everyone).
imagine you have to launch a default function : "f_cup_of_tea", that any normal individual would end up needing after 5 minutes on your website. :
tea_Task_ID = window.setTimeout(f_cup_of_tea, (5*60*1000), 15, 2);
like: function f_cup_of_tea(milk_ml, sugar) { .... }
but unfortunatly, with ten second late, a psychadelic user prefer to get something different than the entire world, and choose a bad_tequila...
you must cancel the delicious " f_cup_of_tea " scheduled within five minutes ... fortunately javascript have thinking of this kind of problem and you can use :
window.clearTimeout(tea_Task_ID);
(but it woorks only if " f_cup_of_tea " are not yet started).
next, you can launch :
tequila_Task_ID = window.setTimeout(f_bad_tequila, (5*1000), 0); // for in 5s, with zero ice...