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?
I'm only fixing your code here, not thinking outside the box. The other answers already gave some pointers for that.
For better type safety, you should declare your callback pointer as follows:
Then, call it as:
Another (better) answer would be to use the
<functional>
header in C++, and declare the function like so:In C++ by itself, you're pretty limited. You need either a multithreaded OS, where you could use a sleep function (you can still have the program continue running with a separate thread), or you need a messaging system, like Windows.
The only other way I see that you can do something is to have a lot of calls scattered throughout the code that calls a function that returns true or false, depending on whether the time has elapsed. The function could, of course, be a callback, but you would still need to call it periodically.
Make
Callback::func
of typevoid (*)()
, i.e.You can call the function this way:
Also, don't busy-wait. Use
ualarm
on Linux orCreateWaitableTimer
on Windows.After C++11 came out, and if your are using c++11 supported compiler, you can use lambda, variadic template function and asynchronous thread to simulate javascript function in c++ easily.
Here is the code I wrote for setTimeOut, it is fully tested:
setTimeOut funtion's definition:
This function accepts variable arguments by using c+11's variadic template, The code can show you how to use it: