3 ms·
And another comparison, SimpleTimer.svelte: <script> let seconds = 0; setInterval(() => { seconds++; }, 1000); </script> <div>{second
by chrismorgan 6y ago
And another comparison, SimpleTimer.svelte:
<script>
let seconds = 0;
setInterval(() => {
seconds++;
}, 1000);
</script>
<div>{seconds} secs have elapsed...</div>
Note that this deliberately functions slightly differently: it uses setInterval rather than repeated setTimeouts. This makes a much more accurate seconds counter, as setTimeout will wait for at least 1000 milliseconds before incrementing seconds and setting another timeout, meaning that you will always count time too slowly, commonly around 1% too slow, but more at times like if JavaScript execution is being throttled because the page is in the background. If you really wanted to do it the other way, it’d be something like this:
<script>
let seconds = 0;
function increment() {
seconds++;
setTimeout(increment, 1000);
}
setTimeout(increment, 1000);
</script>
<div>{seconds} secs have elapsed...</div>
- hombre_fatal 6y agoThe improvement to this sort of time-tracking is not setInterval vs setTimeout but rather "<div>{(Date.now()-startedAt)/1000} secs have elapsed</div>". That way your clock loses its dep on interval frequency.