Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does setTimeout return?

Tags:

javascript

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...

like image 556
Derek 朕會功夫 Avatar asked Apr 09 '12 04:04

Derek 朕會功夫


People also ask

What does setTimeout function do?

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.

What happens when setTimeout is 0?

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.

Does setTimeout create a new thread?

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.

Why is setTimeout executed at last?

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.


1 Answers

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.

like image 75
rid Avatar answered Oct 18 '22 00:10

rid