Javascript setTimeout不起作用。

时间:2014-06-02 23:14:43

标签: javascript settimeout

有人可以解释为什么setTimeout()在这里不能正常工作吗?函数timeLoop()只运行一次。我读了很多类似问题的答案,但都没有帮助。

var Timer = function(){
    var startTime;
    var currentTime;
    var stop = false;
    var me = this;

    this.initTimer = function(){
        document.getElementById('timer').innerHTML = '0';
    }

    this.startTimer = function(){
        this.start = new Date().getTime();
        this.stop = false;
        this.timeLoop();
    }

    this.stopTimer = function(){
        this.stop = true;
    }
    this.timeLoop = function(){
        if(this.stop) return;
        this.currentTime = new Date().getTime() - this.start;
        this.refreshTimer();
        setTimeout(function(){me.timeLoop();}, 10);
    }
    this.refreshTimer = function(){
        document.getElementById('timer').innerHTML = this.currentTime.toString();
    }
}

2 个答案:

答案 0 :(得分:1)

该代码适合我。我怀疑您没有正确创建new Timer()或未正确调用其方法。以下作品:

<!DOCTYPE html>
<html>
<head>
    <title>Some Title</title>
</head>
<body>
<div id='timer'>placeholder</div>
<button onclick="tim.startTimer();">Start</button>
<button onclick="tim.stopTimer();">Stop</button>
<script>
var Timer = function(){
    var startTime;
    var currentTime;
    var stop = false;
    var me = this;

    this.initTimer = function(){
        document.getElementById('timer').innerHTML = '0';
    }

    this.startTimer = function(){
        this.start = new Date().getTime();
        this.stop = false;
        this.timeLoop();
    }

    this.stopTimer = function(){
        this.stop = true;
    }
    this.timeLoop = function(){
        if(this.stop) return;
        this.currentTime = new Date().getTime() - this.start;
        this.refreshTimer();
        setTimeout(function(){me.timeLoop();}, 10);
    }
    this.refreshTimer = function(){
        document.getElementById('timer').innerHTML = this.currentTime.toString();
    }
}
var tim = new Timer();
</script>
</body>
</html>

答案 1 :(得分:0)

您可能需要window.setInterval而不是setTimeout,请阅读此内容。 https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval