Math.sin()
Example
const t = Date.now();
const y = Math.sin(t) * amplitude;const t = performance.now() / 1000;
const y = Math.sin(2 * Math.PI * frequency * t) * amplitude;Raw milliseconds as radians change the phase too fast, while seconds times 2π * frequency give a smooth wave.
Common mistakes
- Passing degrees, like
Math.sin(90), and getting 0.894 instead of 1. - Passing raw
Date.now()and getting a wave that jumps randomly each frame.
Key points
- Code converts degrees to radians with
deg * Math.PI / 180before the call. - Time-based waves divide milliseconds by 1000 and multiply by
2 * Math.PI * frequency.
Interview questions
Why is Math.sin(Math.PI) not 0?
Math.PI is not exact, so the result is a tiny number like 1.22e-16. Compare with a tolerance.
Does Math.sin() take degrees?
No. It takes radians, so convert with deg * Math.PI / 180.