構造扁平化的 setInterval 移動的盒子
<script>
function intervals(delay = 1000, callback) {
return new Promise((resolve) => {
let id = setInterval(() => {
callback(id, resolve)
}, delay);
})
};
intervals(100, (id, resolve) => {
const div = document.querySelector('div');
let left = parseInt(window.getComputedStyle(div).left);
div.style.left = left + 10 + 'px';
if (left >= 200) {
clearInterval(id);
resolve(div);
};
}).then(div => {
return intervals(100, (id, resolve) => {
const div = document.querySelector('div');
let width = parseInt(window.getComputedStyle(div).width);
div.style.width = width - 10 + 'px';
if (width <= 20) {
clearInterval(id)
resolve(div)
}
})
}).then(div => {
return intervals(100, (id, resolve) => {
const div = document.querySelector('div');
let height = parseInt(window.getComputedStyle(div).height);
div.style.height = height + 10 + 'px';
if (height >= 200) {
clearInterval(id);
resolve(div)
}
})
}).then(div => {
div.style.backgroundColor = 'red'
});
</script>