Quốc Cường
Quốc Cường

Reputation: 495

How to use more than one setInterval()?

I want to make the 'box' in the code move to the right and then go back to the left. I tried to use 2 setInterval but it didn't works (or maybe i don't know how to use 2 setInterval).

var box = document.getElementById("box");
var pos = 0;
var toRight = setInterval(move, 10);

function move() {
  if (pos >= 150) {
    clearInterval(toRight);
  } else {
    pos++;
    box.style.left = pos + "px";
  }
}
#container {
  width: 200px;
  height: 200px;
  background-color: red;
  position: relative;
}

#box {
  width: 50px;
  height: 50px;
  background-color: blue;
  position: absolute;
}
<div id="container">
  <div id="box"></div>
</div>
<p id="demo"></p>

I tried so many ways and the code still doesn't run, can some one show me the way to make the 'box' move back from the right side. Thank you.

Upvotes: 1

Views: 132

Answers (2)

junvar
junvar

Reputation: 11574

Your code was a good start, and @j08691's comment is the right direction to take it.

Use 1 interval function but keep track of which direction the box is moving and toggle it when desired.

let box = document.getElementById("box");
let pos = 0, right = true;
setInterval(() => {
  pos += right * 2 - 1;
  if (pos === 0 || pos === 150)
    right = !right;
  box.style.left = pos + "px";
}, 10);
#container {
    width: 200px;
    height: 200px;
    background-color: red;
    position: relative;
}

#box {
    width: 50px;
    height: 50px;
    background-color: blue;
    position: absolute;
}
<div id="container">
    <div id="box"></div>
</div>

Upvotes: 3

Turtlefight
Turtlefight

Reputation: 10700

As an alternative you could also use css animations and skip the javascript part entirely:

@keyframes move {
  from { left: 0; }
  to { left: calc(100% - 50px); }
}

#container {
  width: 200px;
  height: 200px;
  background-color: red;
  position: relative;
}

#box {
  width: 50px;
  height: 50px;
  background-color: blue;
  position: absolute;
  animation: move 2s linear alternate infinite;
}
<div id="container">
  <div id="box"></div>
</div>
<p id="demo"></p>

Upvotes: 0

Related Questions