gpt4 book ai didi

javascript - setInterval 仅触发一次

转载 作者:行者123 更新时间:2023-12-02 17:14:42 25 4
gpt4 key购买 nike

我正在尝试创建一个自包含的计时器,其中所有变量都位于一个对象内。

在大多数情况下,它可以工作,但我可以让它触发一次。我错过了什么?

    function Countdown()
{
this.appId = null;
this.timerId = null;
this.seconds = null;

this.decrementCounter = function (instant)
{
if (instant == null)
return;

instant.tick();
if (instant.seconds === 0)
{
instant.tickEnd();
instant.stop();
}
instant.seconds--;
};
this.tick = function ()
{
var xx = this.appId
};
this.tickEnd = function ()
{
var xx = this.appId
};
this.start = function ()
{
clearInterval(this.timerId);
this.timerId = setInterval(this.decrementCounter(this), 1000);
};
this.stop = function ()
{
clearInterval(this.timerId);
};
}

最佳答案

我稍微修改了您的代码,并将包含 setInterval 的行更改为:

this.timerId = setInterval((function(scope) {
return function() {
scope.decrementCounter(scope);
};
})(this), 1000);

函数在setInterval内部运行,在window范围内运行。它只运行一次,因为您不会仅传递函数本身的结果。您需要返回实际的函数或传递调用它的匿名函数。

jsfiddle 演示:http://jsfiddle.net/2gLdL/1/

关于javascript - setInterval 仅触发一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24542207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com