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.
There is no built in setInterval in C++. you can imitate this function with asynchronous function:
template
void setInterval(std::atomic_bool& cancelToken,size_t interval,F&& f, Args&&... args){
cancelToken.store(true);
auto cb = std::bind(std::forward(f),std::forward(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();
}