Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of JavaScript's setTimeout on qtScript?

Not much to add; what is the equivalent of JavaScript's setTimeout on qtScript?

like image 535
MaiaVictor Avatar asked Jun 28 '12 01:06

MaiaVictor


People also ask

What can I use instead of setTimeout?

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.

Is setTimeout in seconds or milliseconds?

Definition and Usage. The setTimeout() method calls a function after a number of milliseconds. 1 second = 1000 milliseconds.

What is the default time for setTimeout?

0 milliseconds by default.

Is setTimeout async or sync?

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.


1 Answers

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);
like image 105
DerManu Avatar answered Oct 16 '22 23:10

DerManu