简体   繁体   中英

Why does setInterval return the same value when using the Date method

I am trying to get the local seconds from the getSeconds but when I console.log the results by adding the function in setInterval the seconds are the same yet they are increasing. please find my code below;

const time = new Date();
function clock() {
   const seconds = time.getSeconds();
   console.log(seconds)
}
let interval = setInterval('clock()', 1000);

You are assigning the value for time outside (and only once) of your interval-func, therefore it's always the same. Try:

 function clock() { let time = new Date(); const seconds = time.getSeconds(); console.log(seconds) } let interval = setInterval('clock()', 1000);

you create one data object (in some moment) and then you call getSeconds on the same data object so you have the same result

 function clock() { const seconds = new Date().getSeconds(); console.log(seconds) } let interval = setInterval(clock, 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM