Search code examples
c++cocos2d-xdelaycocos2d-x-3.0

Add delay to code execution in C++


Say I need to call a function with 2 seconds delay. In cocos2d-x you can use actions:

auto action = Sequence::create(
    DelayTime::create(2), 
    CallFunc::create(
        [&]() {
            // here is the lambda function that does whatever you want after 2 seconds
        }
    ), 
    NULL
);

runAction(action);

But in order to run the action you need a Node, which in not always available. There are classes that have nothing to do with the Node. So I wonder what is the cross-platform way of adding delay to code execution in C++11?


Solution

  • You can use the std::this_thread::sleep_for function added in the C++11 threading library:

    std::chrono::seconds duration( 2 ); 
    std::this_thread::sleep_for( duration ); // Sleep for 2 seconds.
    

    This will cause the current thread to halt execution for the duration specified in the duration object.