[英]function executed by setInterval() multiple doesn't show results | Javascript
I am making a timer in javascript.我正在用javascript制作一个计时器。 But there is one thing I am not getting.
但有一件事我没有得到。
Here's the code...这是代码...
var time = 0;
var timeInterval;
var testTime;
//Main code which increases the value of variable time by 1 every second until interval is stopped
timeInterval = setInterval(function (){
time++;
testTime = time;
}, 1000);
//Code to stop the interval after 10 seconds.
setTimeOut(function() {
clearInterval(timeInterval);
},10000);
//Expected value -> 10
//I get -> 0
console.log(testTime)
If I am running a function which increases the value of time
by 1
10times by setInterval()
method... Why the value of time
is not updating?如果我正在运行一个函数,它通过
setInterval()
方法将time
值增加1
10 倍......为什么time
值没有更新?
When you call setInterval, you are asking code to run after a certain amount of time.当您调用 setInterval 时,您要求代码在一定时间后运行。 The setInterval function is an example of a function that takes a function as a parameter.
setInterval 函数是一个将函数作为参数的函数示例。
This means that you're declaring a function and asking setInterval to call it at a later time all in one go.这意味着您要声明一个函数并要求 setInterval 稍后一次性调用它。 None of what is inside the function will be called until the interval happens.
在间隔发生之前,不会调用函数内部的任何内容。
Your console.log is not inside either of the functions you gave to setInterval or setTimeout, so it will run straight away.您的 console.log 不在您提供给 setInterval 或 setTimeout 的任何一个函数内,因此它会立即运行。
The order of execution is:执行顺序为:
If you want to fix your code, you can put the console.log in the setTimeout function to ask it to run at the end of the 10 seconds (putting it inside step 7).如果要修复代码,可以将 console.log 放在 setTimeout 函数中,要求它在 10 秒结束时运行(将其放在第 7 步中)。
var time = 0;
// Main code which increases the value of variable time by 1 every second until interval is stopped
var timeInterval = setInterval(function (){
time++;
console.log("time during interval: ", time);
}, 1000);
// Code to stop the interval after 10 seconds.
setTimeout(function() {
clearInterval(timeInterval);
console.log("time at end: ", time);
}, 10000);
Depending on your objective, you might rather simplify your code by calling clearInterval inside your interval function ( if(time > 10) clearInterval(...)
) to reduce the likelihood of a bug.根据您的目标,您可能宁愿通过在区间函数(
if(time > 10) clearInterval(...)
)中调用 clearInterval 来简化代码,以减少出现错误的可能性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.