Search code examples
javascripttimersettimeoutqtscript

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


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


Solution

  • 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);