我可以在JavaScript中制作能够更快地消磨时间的东西吗?
就像在传递现实世界1秒钟时通过JS传递10分钟一样
答案 0 :(得分:4)
可以覆盖setTimeout和setInterval以及Date:
function TimeMachine(timescale = 0.1, code){
const context = Object.create(window);
//setTimeout
const setTimeout = context.setTimeout = function(callb, time){
window.setTimeout(callb,time*timescale);
};
//setInterval
const setInterval = context.setInterval = function(callb,time){
window.setInterval(callb,time*timescale);
};
//Date TODO:resolve timestrings
const now = new window.Date().getTime();
window.setInterval(function(){now+=1/timescale;},1);
const Date = context.Date = function(){
this.getTime=function(){
return now;
};
};
//create Scope with new window
(function(window){
eval("("+code+")()");
})(context);
};
像这样使用:
TimeMachine(0.1,function(){
//execute in time machines context
setInterval(function(){alert("10 seconds passed");},10000);//10secs -> 1sec
//even this should work:
window.setTimeout(function(){alert("test")},1000);
});
我建了一台时间机器:0
参考文献: http://www.instructables.com/id/How-to-Build-a-Time-Machine-Vortex-Distortion-Spa/
答案 1 :(得分:0)
在这里,我创建了一个函数,当有两个参数时。第一个参数是现实世界时间,第二个参数是它对应的虚拟时间。
$v_time(1000,100); // Maps 1 second of real world as 100ms in virtual world
使用两个参数调用该函数来映射它们并创建一个虚拟时间世界。
$v_time(60000) // returns virtual world time corresponding to real world 60 sec;
现在,无论何时需要虚拟时间,都可以根据需要调用该函数。
$v_time=function (rel_time,vir_time) {
if(vir_time) $v_time.offset
= (Math.min(rel_time,vir_time)
/Math.max(rel_time,vir_time));
return rel_time*$v_time.offset;
}
$v_time(1000,100); // Maps 1sec of real world as 100ms of virtual world
setTimeout(function(){
console.log('hello');
},$v_time(10000)); // 10sec of real world will return 1s of virtual world.

以1秒的虚拟世界做10分钟的现实世界
$v_time(10*60*1000,1000);
现在致电$v_time(your_time);