如何在JavaScript中减慢速度并加快时间 [英] How to slow down and speed up time in JavaScript

查看:61
本文介绍了如何在JavaScript中减慢速度并加快时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了一个如何在JavaScript中暂停时间的示例.示例在此处 http://jsfiddle.net/suska/n4g5U/

I implemented an example of how to pause time in JavaScript. The example is here http://jsfiddle.net/suska/n4g5U/

// Update of Date class to modify getTime method.
Date.prototype.origGetTime = Date.prototype.getTime;
Date._lastPausedAt;
Date._stopDuration = 0;
Date.prototype.getTime = function() {
    if (Date._lastPausedAt) {
        return Date._lastPausedAt.origGetTime() - Date._stopDuration;
    }
    return new Date().origGetTime() - Date._stopDuration;
};
Date.isPaused = function() {
    return Date._lastPausedAt != null;
};
Date.pause = function() {
    if (!Date._lastPausedAt) {
        Date._lastPausedAt = new Date();
    }               
};
Date.unpause = function() {
    if (Date._lastPausedAt) {
        Date._stopDuration += new Date().origGetTime() - Date._lastPausedAt.origGetTime();
        Date._lastPausedAt = null;
    }
};

有什么主意我该如何修改示例以降低速度并加快功能?

Any idea how can I modify the example to do a slow down and speed up functionality?

推荐答案

在dooxe的答案上写一个变体,以避免在两次时间扭曲之间切换时突然跳动.

Wrote a variant on dooxe's answer to avoid the sudden jumps when changing between time warps.

var milli = Date.prototype.getTime;
var lastTime = (new Date).getTime();
var curTime = 0;
Date.prototype.getTime = function(){
    var actualTime = milli.call(this);
    curTime += (actualTime - lastTime) * Date._speed;
    lastTime = actualTime;
    return curTime;
};

这篇关于如何在JavaScript中减慢速度并加快时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆