Skip to content

Enhanced Async Calling

Jing Lu edited this page Jun 2, 2013 · 9 revisions

The built-in function setTimeout and setInterval calls specified function after a specified milliseconds. These two functions forces the ScriptRunningMachine to start a new thread to continue run script.

The setTimeout and setInterval functions performs asynchronous calling in ReoScript.

setTimeout

setTimeout function runs specified code once after a specified milliseconds.

function start() { }
setTimeout(start, 1000);        // call 'start' after one second

setTimeout returns a counter which could be used when you want to cancel the asynchronous-calling:

var id = setTimeout(start, 1000);
...
clearTimeout(id);

setInterval

setInterval function runs specified code repeatedly at specified intervals (in milliseconds).

function show_current_time() {
    console.log('the time is ' + new Date());
}

setInterval(show_current_time, 1000);

Like setTimeout the counter id could be used to cancel this calling:

var id = setInterval(show_current_time, 1000);
clearInterval(id);

Script will keeps running after Run

Assume that code in below will be executed:

function check_run() {
    if (!request_quit) {
        setTimeout(check_run, 1000);
    }
}

This script will keeps check the request_quit flag per second. If request_quit is false, setTimeout will be invoked again and again. This script will keeps running after check_run to be invoked until the request_quit be set to true.

However, if your code may causes the script keeps running like above, you need to use IsRunning to check whether the script currently is running on.

bool running = srm.IsRunning;

If running is true, it means script is running now. If you want to kill it immediately, you could use ForceStop method:

srm.ForceStop();

Pass arguments when calling setTimeout and setInterval

ReoScript allows you pass arguments when you calling setTimeout or setInterval functions, the syntax is:

setTimeout( code, delays, arg1, arg2, ..., argn );

In the example as below an object will be created and passed as argument 'obj' to function 'run':

function run(obj) {
    console.log('Object is ' + obj.name);
}

setTimeout(run, 1000, {name: 'obj1'});

After waiting one second, the following text will be printed out:

Object is obj1