Passing an argument to requestAnimationFrame twice

I used the script from to create an animation of an oscillating sine wave but I want to display 2 sine waves and eventually 4 so I need to pass an argument to window.requestAnimationFrame() I was able to get the first variable to be passed working but when I called window.requestAnimationFrame again and passed a new variable, it stopped working. If I call requestAnimationFrame again by uncommenting the following line, it doesn’t work any more:

window.requestAnimationFrame(function(timestamp) { draw(canvas_2);});

This is my codepen:

A solution was posted here:

1 Like

Hi @makamo661, another possibility would be to wrap requestAnimationFame() in a function to kick off the loop:

function loop(callback, ...args) {
  window.requestAnimationFrame(() => {
    loop(callback, ...args)

Which you’d then use like so:

loop(draw, document.getElementById('photon_1'))
loop(draw, document.getElementById('photon_2'))

This way you can pass around the canvas references rather than querying them anew on each frame, and you can handle multiple draw functions independently (e.g. when starting another one at some later point).