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...
The setTimeout function is a native JavaScript function. It sets a timer (a countdown set in milliseconds) for an execution of a callback function, calling the function upon completion of the timer. JavaScript's setTimeout method can prove handy in various situations.
Invoking setTimeout with a callback, and zero as the second argument will schedule the callback to be run asynchronously, after the shortest possible delay - which will be around 10ms when the tab has focus and the JavaScript thread of execution is not busy.
No, it doesn't. "Execution context" doesn't mean "thread", and until recently Javascript had no support for anything resembling threads. What actually happens is that an event is pushed onto the event queue that's set to execute in the number of milliseconds specified by the second argument to SetTimeout/SetInterval.
setTimeout schedules the function for execution. That scheduler doesn't do its thing until after the current thread yields control back to the browser, e.g. after the last logging statement has executed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With