Mar 232015
 
Article Javascript

In most programming languages, there is a built-in function sleep(), wait() or similar that will suspend the execution of the program or script for a given amount of time, normally expressed in milliseconds, without CPU consumption. A call to this function is commonly used inside a loop that check for the availability of some resource required to continue the execution.

In javascript, there is no such function, but a setTimeout() function that schedules the execution of a function after a specified number of milliseconds.

setTimeout can also be used inside a loop to wait for the availability of some required resource, as in the following example:

As can be seen in the example above, the first argument in the call to setTimeout is a reference to the function to be scheduled for execution.

But, if that function expects arguments, the call to setTimeout must be done passing an anonymous function, that just call the function we want to execute, passing the desired arguments to it.

Example:

And that’s all!

 Posted by at 12:42 pm

 Leave a Reply

(required)

(required)