[英]setTimeout will not delay
我最近正在制作一個計時器對象和一個滴答函數,它們會根據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
上this.tick()
在tick()
函數中調用this
函數時,您已經在引用tick
函數, 因此您想使用 setTimeout(this, 1000);
並且您的計時器將正常工作。
有關解決方案,請參見此提琴: https : //jsfiddle.net/sg7yf6r4/
閱讀有關此問題的更多信息: Javascript對象從自身調用函數
setTimeout
的第一個參數應該是一個函數。 但是,您將其傳遞給函數的結果。 因此,而不是setTimeout(this.tick(), 1000, $(this));
您應該使用setTimeout(this.tick, 1000, $(this));
。
您傳遞的是已執行的函數,而不是對setTimeout
的函數引用。 要傳遞函數本身,請刪除括號。 其次,要確保this
仍然是當前this
時候tick
最終被調用,使用.bind(this)
。
請注意, setTimeout
的第三個參數會將該值傳遞給tick
,在您的情況下這沒有用。 注意: $(this)
可能是其他一些代碼的剩余部分,因為$
通常與不使用的jQuery一起使用。
因此,綜合考慮一下:
setTimeout(this.tick.bind(this), 1000)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.