Using setInterval() in C++

后端 未结 2 1638
梦毁少年i
梦毁少年i 2021-02-06 16:13

In JavaScript, there is a function called setInterval(). Can it be achieved in C++? If a loop is used, the program does not continue but keeps calling the function.

2条回答
  •  余生分开走
    2021-02-06 16:43

    Use std::thread to achieve.

    //  should have been included
    void setInterval(auto function,int interval) {
        thread th([&]() {
            while(true) {
                Sleep(interval);
                function();
            }
        });
        th.detach();
    }
    //...
    setInterval([]() {
        cout<<"1 sec past\n";
    },
    1000);
    

提交回复
热议问题