Interviewer: Move the div to the right in X time with Y FPS
UnAccademy Senior Front End Developer Interview Experience
I faced this question in a front end interview, this questions was followed by multiple sub questions and this was the only questions interviewer asked.
Although I got stuck in last part and did not make it to the next round. But I got many learnings and also shared some of the learning to the interviewer as well.
Here I am sharing the experience so that others can make use of it and I can also have it somewhere in my mind.
Problem Statement 1: Create a ball of size 20px.
Problem Statement 2: On Click of the ball, Move it to 200px right, from its current position.
I did it using position:relative
to make div
moveable, as by default all HTML elements are static.
And creating a ref
variable in my component. and changing the style.left
value onClick
Problem Statement 3: Move it with some kind of Animation.
This was pretty much straight, I added transition: left 0.4s linear;
and ran the app.
And this was the behavior:
I was shocked to see this, and also the interviewer, we both were expecting that the ball will move with animation.
At that time, we haven’t gave it priority and moved on to next step.
.
.
But, It was a shocker for me, as I’ve performed these type of animation and I was curious to know why it didn’t worked at that time.
The reason why transition
didn’t work was pretty simple. I missed to provided the initial value.
The browser needs to explicitly know what the start and end values are in order to calculate the transition sequence.
I was assuming that the starting value would the be property’s default value or its current position, but that is not the case. The start and end values must be explicitly declared
Once I have the starting value as 0, everything started working:
Problem Statement 4: Move the ball by 200px to the right, in 3 Seconds with a FPS of 30.
Here I messed up the things. I got confused in the basic elementary concept of calculating speed using distance and time. At that time my mind was telling me that it is distance x time
. But it is distance/time
. And this was the reason what I can think of that I did not make it to the next round.
Here is the final result which I tried after the interview:
And the code:
Problem Statement 5: Do the animation only once, on the next click nothing should happen.
Here he was expecting that I will either use any other state variable or remove the click
event listener from the button.
But I did something new, that was a learning for him as well:
We can pass options
object to the addEventListener
method. And there exists an option called once
if we set it to true
then the event will be performed only once, and after that the listener will be remove automatically.
So I removed the onClick
prop, and simply wrote this code:
After this the interview was done and it was a great experience. I hope this will make you learn something new.
Thank for reading :)