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.
Use std::thread
to achieve.
// <thread> 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);
There is no built in setInterval
in C++. you can imitate this function with asynchronous function:
template <class F, class... Args>
void setInterval(std::atomic_bool& cancelToken,size_t interval,F&& f, Args&&... args){
cancelToken.store(true);
auto cb = std::bind(std::forward<F>(f),std::forward<Args>(args)...);
std::async(std::launch::async,[=,&cancelToken]()mutable{
while (cancelToken.load()){
cb();
std::this_thread::sleep_for(std::chrono::milliseconds(interval));
}
});
}
use cancelToken
to cancel the interval with
cancelToken.store(false);
do notice though, that this mchanism construct a new thread for the task. it is not usable for many interval functions. in this case, I'd use already written thread-pool with some sort of time-measurment mechanism.
Edit : example use:
int main(int argc, const char * argv[]) {
std::atomic_bool b;
setInterval(b, 1000, printf, "hi there\n");
getchar();
}