【发布时间】:2020-05-07 04:34:25
【问题描述】:
我写了一个 SetInterval 和 SetTimeOut 函数作为 JavaScript 函数,但我不能设置低 100 毫秒,也不能调用两个 SetInterval。请帮帮我!
包括
#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>
using namespace std::chrono;
using namespace std;
milliseconds ms = duration_cast<milliseconds>(
system_clock::now().time_since_epoch()
);
带参数函数的SetTimeOut
template <typename Proc, typename T>
void SetTimeOut(T & val, Proc p, unsigned long long n) {
unsigned long long def = ms.count(); // starting point
unsigned long long ds = ms.count() + n; // the time what need become equal to def
while (def != ds) {
milliseconds ms = duration_cast<milliseconds>(
system_clock::now().time_since_epoch()
); // time updates
def = ms.count(); // converting to nums
}
p(val); // calling the main function
}
相同,但调用无参数函数
template <typename Proc>
void SetTimeOut(Proc p, unsigned long long n) {
unsigned long long def = ms.count() ;
unsigned long long ds = ms.count() + n;
while (def != ds) {
milliseconds ms = duration_cast<milliseconds>(
system_clock::now().time_since_epoch()
); // time updates
def = ms.count();
}
p(); // Main function calling
}
p - 我们要调用的函数,n - 应该经过多少时间,s - 应该重复多少次。 SetInterval 带无参数函数
template <typename Proc>
void SetInterval(Proc p, unsigned long long n, long long s) {
//here there are call in turn of function SetTimeOut
for (int i = 1; i != s + 1; i++) SetTimeOut(p, n * i);
}
//Same, but for parameter function
template <typename T, typename Proc>
void SetInterval(T val, Proc p, unsigned long long n, long long s) {
for(int i = 1; i != s+1; i++) SetTimeOut(val, p, n * i);
}
//Example with struct
struct Car{
string model;
double speed;
int fuel;
};
主要功能
int main() {
Car Car;
int i = 1;
Car.fuel = 200;
Car.speed = 10.2;
//Example with lambda function.
SetInterval(Car,[&](struct Car){
Car.speed += 1.9;
Car.fuel -= 1.2;
cout << Car.speed << " " << Car.fuel << endl;
}, 900, 10); // it will end after 10 calls with 0.9 sec interval
//Second Example, which is not working
SetInterval(i, [&](int i){ i++; cout << i << endl;}, 500, 5);
}
我认为是因为通话时间过长,但我不知道如何解决。
【问题讨论】:
-
为什么问题标记为
c?
标签: c++ windows visual-c++ console-application