kidapu
5/14/2016 - 2:12 PM

of_settimeout_sample.cpp

of_settimeout_sample.cpp

#pragma once

#include "ofMain.h"

#include <functional>
#include <chrono>
#include <future>
#include <cstdio>

// reference : https://stackoverflow.com/questions/14650885/how-to-create-timer-events-using-c-11/14665230#14665230

class later
{
public:
    template <class callable, class... arguments>
    later(int after, bool async, callable&& f, arguments&&... args)
    {
        std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
        
        if (async)
        {
            std::thread([after, task]() {
                std::this_thread::sleep_for(std::chrono::milliseconds(after));
                task();
            }).detach();
        }
        else
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(after));
            task();
        }
    }
    
};


class ofApp : public ofBaseApp
{
public:
    int _hue = 0;
    void setup()
    {
        ofSetColor(255);
        ofBackground(0);
        ofSetCircleResolution(50);
    }
    
    void update()
    {
    }
    
    void draw()
    {
        ofSetColor( ofColor::fromHsb( _hue, 255, 255 ) );
        ofDrawCircle(ofGetWidth()*0.5, ofGetHeight()*0.5, sin(ofGetElapsedTimeMillis()*0.005)*100.0);
    }

    void keyPressed(int key)
    {
        switch(key)
        {
            case ' ':
                later later_test1(1000, true, [&](){
                    _hue += 50;
                    cout << "hue:" << _hue << endl;
                });
                break;
        }
    }
};