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:

function my_process() {

    // Check for the availability of the required resource
    if (! resource_available) {
        // Not available yet. -> Try again in 100ms
        setTimeout(my_process,100);
        // and finish for now
        return;
    }
    // At this point, the resource is available -> 
    // Run the code that depends on the availability of the resource
    ...
}

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:

function other_process(data) {

    // Check for the availability of the resource
    if (! resource_available) {
        // Schedule the execution of an anonymous function, that just calls other_process
        setTimeout(function() {
                other_process(data);
            },100);
        // and finish for now
        return;
    }
    // At this point, the resource is available -> 
    // Run the code that depends on the availability of the resource
    ...
}

And that’s all!

 Posted by at 12:42 pm

 Leave a Reply

(required)

(required)