Why do the following two codes perform differently? There is only one difference between the two ends of the code which part 2 has a setTimeout
// 1
var div = document.querySelector('.move');
div.classList.add('start');
div.classList.add('move-active');
requestAnimationFrame(() => {
div.classList.remove('start');
div.classList.add('end');
});
div.style.display = 'block';
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>test</title>
<style>
.move {
position: absolute;
width: 100px;
height: 100px;
background-color: red;
}
.start {
transform: translateX(0);
}
.move-active {
transition: transform 3s ease;
}
.end {
transform: translateX(100px);
}
</style>
</head>
<body>
<div class="move" style="display: none;"></div>
</body>
</html>
// 2
setTimeout(() => {
var div = document.querySelector('.move');
div.classList.add('start');
div.classList.add('move-active');
requestAnimationFrame(() => {
div.classList.remove('start');
div.classList.add('end');
});
div.style.display = 'block';
}, 0);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>test</title>
<style>
.move {
position: absolute;
width: 100px;
height: 100px;
background-color: red;
}
.start {
transform: translateX(0);
}
.move-active {
transition: transform 3s ease;
}
.end {
transform: translateX(100px);
}
</style>
</head>
<body>
<div class="move" style="display: none;"></div>
</body>
</html>
- In the first part of the code, each browser refresh will have animation effect
- But in the second part of the code, each browser refresh will have animation effect
Why does setTimeout have different effects on the same code? Isn't setTimeout putting the whole code block in the event loop thread and then executing it in the JS engine thread?