Reputation: 89
I have saw the problem Moving Div Box using javascript and the top upvote answer is good .
But if I want to get the feacture like CSS3 does ,how can I do?
.cuble{
height: 100px;
width: 100px;
background-color: blue;
transition: all 3s ease-in-out;
}
.cuble:hover{
transform: translateX(500px);
}
<!Doctype html>
<html>
<body>
<div class="cuble">
</div>
</body>
I don't need ease-in-out effect .I just want hover the div once and even if I mouseout the div ,the div will also moving from left to right until the setting time. But the Moving Div Box using javascript don't meet the requirement.
I try to use Promise to achieve the goal ,here is my Javascript code .(anyway,maybe I just want to learn deep about javascript async performance)
var cuble = document.querySelector('.cuble');
cuble.onmouseover = function(e) {
for (var i = 0; i < 100; i++) {
var pixels = 5 * i + "px";
delay(100)
.then(() => cuble.style.marginLeft = pixels)
}
}
function delay(t) {
return new Promise(function(resolve) {
setTimeout(resolve, t)
});
};
How can I fix my Javascript code and meet the requirement?
Upvotes: 0
Views: 223
Reputation: 47667
The issue is you're creating one hundred promises each with a 100ms delay almost instantly, so they all firing almost instantly.
One way to remedy the issue is increase the delay for each subsequent promise. And you also have to pass the corresponding pixels for each resolve. Something like:
var cuble = document.querySelector('.cuble');
cuble.onmouseover = function(e) {
for (var i = 0; i < 100; i++) {
var pixels = 5 * i + "px";
delay(i * 20, pixels)
.then((p) => cuble.style.marginLeft = p)
}
}
function delay(t, pixels) {
return new Promise(function(resolve) {
setTimeout(() => resolve(pixels), t)
});
};
An example with no promises and just one function being created and called, instead of creating new function for every step:
var cuble = document.querySelector('.cuble');
cuble.onmouseover = function() {
var left = 0,
ival = setInterval(move, 5);
function move() {
if (left === 500) clearInterval(ival);
cuble.style.marginLeft = left++ + 'px';
}
}
Upvotes: 1