kaluma-project / kaluma

A tiny JavaScript runtime for RP2040 (Raspberry Pi Pico)
https://kalumajs.org
Apache License 2.0
647 stars 37 forks source link

Millisecond in Date object updates only once every second #625

Closed kashyap1113 closed 1 year ago

kashyap1113 commented 1 year ago
Package Version
Kaluma CLI 1.4.0
Kaluma kaluma-rp2-pico-w-1.1.0-beta.4.uf2

I have set an interval to console log every 500 milliseconds. It is even printed every 500 milliseconds. But the value of milliseconds in date object is not updated after 500 milliseconds. It updates only every second.

Code

const printHello = () => {
    return setInterval(() => {
        console.log(new Date().getTime(),"hello from other interval");
    }, 500);
}

const main = () => {
    printHello();
}

main();

Output

14000 hello from other interval
14000 hello from other interval
14000 hello from other interval
15000 hello from other interval
15000 hello from other interval
16000 hello from other interval
16000 hello from other interval
17000 hello from other interval
17000 hello from other interval
18000 hello from other interval
18000 hello from other interval
19000 hello from other interval
19000 hello from other interval
20000 hello from other interval
20000 hello from other interval
communix commented 1 year ago

@kashyap1113 setInterval() function works well and it call callback function every 500ms. But resolution of the Date().getTime() is 1s because this function use RTC clock. Now default of the PICO board use 1ms RTC timer. You can see the same value twice because function is called twice in a second but Date().getTime() return the same time.

please use millis() function to get milliseconds timestamp instead of new Date().getTime().

https://kalumajs.org/docs/api/timers#millis