Not much to add; what is the equivalent of JavaScript's setTimeout on qtScript?
The setInterval method has the same syntax as setTimeout : let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...) All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time.
Definition and Usage. The setTimeout() method calls a function after a number of milliseconds. 1 second = 1000 milliseconds.
0 milliseconds by default.
setTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack. In other words, you cannot use setTimeout() to create a "pause" before the next function in the function stack fires.
Here's how you can extend your script language, by providing a self-contained C++ method (no need for bookkeeping of timer ids or so). Just create the following slot called "setTimeout":
void ScriptGlobalObject::setTimeout(QScriptValue fn, int milliseconds)
{
if (fn.isFunction())
{
QTimer *timer = new QTimer(0);
qScriptConnect(timer, SIGNAL(timeout()), QScriptValue(), fn);
connect(timer, SIGNAL(timeout()), timer, SLOT(deleteLater()));
timer->setSingleShot(true);
timer->start(milliseconds);
} else
context()->throwError(tr("Passed parameter '%1' is not a function.").arg(fn.toString()));
}
And introduce that slot as function to the global object of your script engine. This can be done in different ways, e.g. just creating a QScriptValue-function via the QScriptEngine instance, and setting an accordingly named property on the engine's existing global object. In my case however, the entire ScriptGlobalObject instance is set as new global object, like this:
mScriptGlobalObject = new ScriptGlobalObject(this);
engine->setGlobalObject(engine->newQObject(mScriptGlobalObject));
Note that if you want to use "context()" as shown in the setTimeout code above, your ScriptGlobalObject should derive also from QScriptable, like this:
class ScriptGlobalObject : public QObject, protected QScriptable
In the script you can now use setTimeout to have a method invoked at a later time (as long as the QScriptEngine instance from which it originates isn't deleted in the meantime):
setTimeout(function() {
// do something in three seconds
}, 3000);
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