【问题标题】:setTimeout will not delaysetTimeout 不会延迟
【发布时间】:2017-05-30 22:29:11
【问题描述】:

我最近正在制作一个计时器对象和一个计时函数,它会根据 setTimeout 循环每秒计时一次。但是,滴答作响并没有延迟。如果你尝试下面的代码,你会发现时间数在几秒钟内就增加到了数千。如果有的话,我做错了什么?

<html>

<head>

</head>
    <button onclick="startTimer()">Start</button>
    <button onclick="stopTimer()">Stop Timer</button>
    <button onclick="readTimer()">Read Timer</button>

    <script>
function tick(){
    console.log("TICK TOCK");
    if(this.running == true){
        this.time += 1;
        console.log("HELLO!");
        setTimeout(this.tick(), 1000, $(this));
    }

}

function start(){
    this.running = true;
    this.tick();
}
function read(){
    return this.time;
}
function stop(){
    this.running = false;
}

function reset(){
    if(this.running == false){
        this.time = 0;
    }else {
        this.time = 0;
    } 
    this.tick();
}
function timer(){
    this.running = false;
    this.time = 0;
    this.start = start;
    this.read = read;
    this.stop = stop;
    this.reset = reset;
    this.tick = tick;
}
var t = new timer();

        function startTimer(){
            t.start();
        }   
        function stopTimer(){
            t.stop();
        }
        function readTimer(){
            alert("This is the current Timer Reading: " + t.time);
        }





    </script>
</html>

【问题讨论】:

  • 您将一个已执行的函数而不是一个函数传递给setTimeout。做setTimeout(this.tick.bind(this), 1000).
  • 有效!非常感谢。如果没有你的帮助,我不会解决这个问题。

标签: javascript settimeout


【解决方案1】:

您的错误是您在this.tick() 上调用setTimeOut。当你在tick() 函数中调用this 时,你已经在引用tick 函数,所以你想使用setTimeout(this, 1000);,你的计时器会正常工作。

请参阅此小提琴以获取解决方案:https://jsfiddle.net/sg7yf6r4/

阅读有关该问题的更多信息:Javascript objects calling function from itself

【讨论】:

  • 出于某种原因,将代码从 setTimeout(this.tick(), 1000);到 setTimeout(this, 1000) 产生错误:Uncaught SyntaxError: Unexpected identifier.
  • 再次检查您的代码;这是一个按预期工作的 CodePen:codepen.io/anon/pen/LyKwXG 确保您没有拼写错误。
  • 我检查了我的拼写,找不到任何不工作的原因,但它仍然只运行一次刻度功能,然后留下错误消息。 function tick(){ console.log("TICK TOCK"); if(this.running == true){ this.time += 1; console.log("你好!");设置超时(这个,1000); } }
  • 语法错误发生在哪一行?你能把那行专门贴出来吗?
  • 对。 chrome 中的控制台日志在 html 文件中没有给出一行,而是给出了:“VM80:1 Uncaught SyntaxError: Unexpected identifier 。”这可能没有帮助是吧。实际上,我将 CodePen 的代码复制到了我的 html 文件中,它仍然会出现同样的错误。也许我的 chrome 浏览器坏了。
【解决方案2】:

setTimeout的第一个参数应该是一个函数。但是,您将函数的结果传递给它。所以你应该使用setTimeout(this.tick, 1000, $(this));,而不是setTimeout(this.tick(), 1000, $(this));。

【讨论】:

  • 这给了我这个错误:“Uncaught ReferenceError: $ is not defined”
【解决方案3】:

您传递的是 已执行 函数,而不是对 setTimeout 的函数引用。要传递函数本身,请删除括号。其次,要确保在最终调用 tick 时 this 仍然是当前的 this,请使用 .bind(this)。

注意setTimeout 的第三个参数会将该值传递给tick,这在您的情况下没有用。注意:$(this) 可能是一些其他代码的残余,因为 $ 通常与您没有使用的 jQuery 一起使用。

所以综合起来,做:

setTimeout(this.tick.bind(this), 1000)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 2012-09-19
    • 2016-08-09
    • 2016-11-15
    相关资源
    最近更新 更多