setInterval 只触发一次 [英] setInterval fires only once

查看:72
本文介绍了setInterval 只触发一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a self contained timer where all variables are inside a object.

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

For the most part it works but I can get this to fire once. What am I missing?

    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 的行更改为:

I modified your code a bit and changed the line containing setInterval to this:

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

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

The functions run inside of setInterval run in the window scope. It only runs once, because you don't pass the function itself just the result of it. You need to return the actual function or pass an anonymous function which calls it.

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

jsfiddle demo: http://jsfiddle.net/2gLdL/1/

这篇关于setInterval 只触发一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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