Is it true that if possible I should never use setInterval & setTimeout?
Asked Answered
C

3

17

I am learning to code in JavaScript. I am programming something with some timed mouse animation. I'm just about to add some code which draws the mouse path.

It's going to be something that takes the mousemove event, and every time the mouse moves draw a new line path on Canvas. And with time, that path is going to be more transparent until it disappears. Of course, new paths are always going to be opaque so there's a continuous movement.

I figured out a way I can do this with just requestanimationframe. Basically every time a new mousemove event occurs, I will add that mouse path coordinates to an array of objects called mousePathArray. The object will carry the path coordinates and an "animationStage" counter. This counter will basically determine how transparent the path will be at that stage of the 'animation'. (Later stages will mean more transparent.)

Then every animation frame I will call a function that will go through all the objects in the array and draw the lines according to their coordinates and animationStage counter, will increase the counter by 1 and will remove the array objects if the animationStage counter reaches the end number (which could be 50 or something).

This can all be done, but it sounds like instead of all of that, it would be much easier to do by just introducing a setInterval function that will be called with a set interval every time the mouse moves.

So is it worth it doing the long way? Would it be faster or maybe just be better JS practice to not use setInterval and rAF together?

After writing all this down I actually wrote the rAF-only code that I talked about above. It's too long to paste here but the rules need it. Here it is on jsfiddle: http://jsfiddle.net/06f7zefn/2/

(I'm aware there are a lot of inefficiencies and probably terrible coding practice but bear with me, I'm 5 days old in this! I could make an isDrawing? boolean instead of calling animate() on every frame, and I can just do ctx.moveTo() once with the rest being LineTo() without having to to moveTo() every iteration since one point originates from where the other left off)

If I could get across the main idea I'm talking about, that is where I am asking for your opinion. Instead of making everything related to timing originate from the rAF call could it be better to use setInterval or setTimeout here instead?

var canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);

var ctx = canvas.getContext('2d');

var currentPosX, currentPosY, prevPosX, prevPosY;
var mousePathArray = [];

canvas.addEventListener ('mousemove', mouseOp);


function mouseOp (mouseEvent) {
    prevPosX = currentPosX;
    prevPosY = currentPosY;
    currentPosX = mouseEvent.clientX;
    currentPosY = mouseEvent.clientY;
    mousePathArray.push( {
        x1: currentPosX,
        x2: prevPosX,
        y1: currentPosY,
        y2: prevPosY,
        animStage: 0
    });
}

function animate () {
    var anims = mousePathArray.length;
    if (anims!=0) {
        for (i=0; i<anims; i++) {
            if (mousePathArray[i].animStage == 20) {
                mousePathArray.splice(i, 1);
                i--;
                anims--;
                continue;
            }

            drawLine(mousePathArray[i].x1, mousePathArray[i].x2, mousePathArray[i].y1, mousePathArray[i].y2, 1 - (mousePathArray[i].animStage * 0.05));
            mousePathArray[i].animStage ++;
        }
    }
}

function drawLine (x1, x2, y1, y2, alpha) {
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.strokeStyle = "rgba(150, 20, 150," + alpha +")";
    ctx.stroke();
}

animloop();

function animloop(){
  window.requestAnimationFrame(animloop);
  gameLoop();
}

function gameLoop() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    animate();
}
Colloquial answered 9/6, 2015 at 3:49 Comment(4)
Define "better". More robust? Greater support? Simpler maintenance? Greater library dependencies?Kurdish
Good question. I am not exactly sure how I would define better code as I'm new at this, but I was trying to look at it from a more dependable code that's less prone to bugs, and maybe faster to boot.Colloquial
Ask yourself the question: Does the animation look the same with 5fps and 120fps? If your answer is no, then your algorithm has chosen the wrong method.Pentlandite
My animation's timing depends on the last frame that was called. So if I had, say, a 5 frame animation it would take one second to go through it once on 5fps, whereas it'd take less than 0.1 seconds under 60 fps.Colloquial
C
26

I don't think using setInterval or setTimeout is bad practice. Using setTimeout is bad practice when you want to do something in the future, but you don't exactly know when you will be able to do that. For example, this is bad practice:

makeHeavyDomMovements();
setTimeout(function () {
  //with 3000 timeout I'm sure any device has made my changes
  makeNextMove();
}, 3000);

the correct way was:

makeHeavyDomMovements().
then(function () {
   makeNextMove();
});

If you want to do something in future like respond to a user action 100ms later, it's best practice to use setTimeout or if you want to put something in browser queue, you should use setTimeout (or use a worker if needed).

It's the same as setInterval, if you are using to do something that should be done every x milliseconds, well you are using it correctly and it's not bad practice, here is a bad usage of setInterval:

var dbInterval = setInterval(function () {
  if (dbIsReady()) {
    clearInterval(dbInterval);
    fireReadyEvent();
  }
}, 300);

And here is a regular usage of setInterval:

setInterval(function () {
  runSync();
}, 600000);

Bad practices and good practices are defined by the way you use your environment tools, not the tools themselves.

Canter answered 9/6, 2015 at 4:48 Comment(3)
Do you mean "future" instead of "feature"? (twice)Pentlandite
Thanks I corrected many spelling issues, I think you want to take an other look.Canter
Be careful with using setTimeout as a scheduler because some browsers pause timers when devices are put to sleep (I see you, iOS Safari!) As an example, if you're hoping to do something at a specific time, that timeout will be offset by the amount of time the user's device is asleep since it was created.Primipara
B
3

Luz Caballero does a fair job of describing why rAF is a useful replacement for setInterval:

https://dev.opera.com/articles/better-performance-with-requestanimationframe/.

As for me, I now use rAF instead of setInterval because rAF has some built-in usefulness that would require additional coding with setInterval:

  • rAF will attempt to synchronize its calls with the display refresh cycle. This gives the code in the loop the "best chance" to complete between the refresh cycles.

  • If the tasks in loop#1 can't complete before loop#2 is requested, then the new loop#2 won't be called until the incomplete loop#1 is completed. This means the browser won't be overworked with a backlog of accumulated loops.

  • If the user switches to a different browser tab then loops in the current tab are suspended. This allows processing power to shift to the new tab instead of being used in the now invisible loop tap. This is also a power-saving feature on battery powered devices. If you want the loop to continue processing while a tab is unfocused you must use setInterval.

  • The rAF callback function automatically gets a high-precision timestamp argument. This allows rAF loops to calculate & use elapsed times. This elaped time can be used to (1) delay until a specified elapsed time has occurred or (2) "catch up" on time based tasks that were desired but were unable to be completed.

Blasphemous answered 9/6, 2015 at 17:35 Comment(0)
A
0

you can use them if you are 100% sure that it is the exact time you need you. if it is an ambiguous situation then not to use it. if you are using a javascript framework look for a lifecycle hooks e.g in angular use Angular life cycle hooks.

Adsorbate answered 16/1, 2020 at 15:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.