Alex Rivera | Logout

Equivalent to window.setTimeout() for C++

Asked 2010-03-20T22:39:29.023
11

In javascript there's this sweet, sweet function window.setTimeout( func, 1000 ) ; which will asynchronously invoke func after 1000 ms.

I want to do something similar in C++ (without multithreading), so I put together a sample loop like:

    #include <stdio.h>

    struct Callback
    {
      // The _time_ this function will be executed.
      double execTime ;

      // The function to execute after execTime has passed
      void* func ;
    } ;

    // Sample function to execute
    void go()
    {
      puts( "GO" ) ;
    }

    // Global program-wide sense of time
    double time ;

    int main()
    {
      // start the timer
      time = 0 ;

      // Make a sample callback
      Callback c1 ;
      c1.execTime = 10000 ;
      c1.func = go ;

      while( 1 )
      {
        // its time to execute it
        if( time > c1.execTime )
        {
          c1.func ; // !! doesn't work!
        }

        time++;
      }
    }

How can I make something like this work?

Edit
Report

1 Answer

0

Another (better) answer would be to use the <functional> header in C++, and declare the function like so:

#include <functional>

function<void ()> func ;

// assign like
func = go ; //go is a function name that accepts 0 parameters
// and has return type void

// exec like
func() ;
answered 2011-12-14T15:57:27.830

Your Answer