랜덤 로또번호 뽑기 ( setInterval() )
지난 포스팅에서 자바스크립트로 랜덤한 번호 6개를 html화면에 출력하는 방법을 알아보았다.
https://coding-heading.tistory.com/7
javascript를 html으로 출력하기
어제 생성했던 로또 번호를 브라우저 화면에 출력하는 방법을 알아보겠다. 어제 스크립트를 만들고 그 결과를 콘솔창에서 확인 했다. https://coding-heading.tistory.com/6 랜덤으로 로또 번호 생성하기
coding-heading.tistory.com
더 나아가 아래와 같은 모습으로 뭔가 작동하고 있다는 느낌을 주고싶어져 아래 영상까지 만들어 가는 과정을 올려겠다.
1. html 코드
<div class="ran">
<button class="tit" onclick="window.location.reload()">추첨</button>
<br>
<h3 id="ran">??, ??, ??, ??, ??, ??</h3>
<br>
</div>
<div class="wrapper">
<div class="rollbutton">
<input type="button" value="시작" onclick="start();" />
<input type="button" value="중지" onclick="stop();" />
</div>
</div>
2-1. javascript 코드
<script>
let isStart = false;
function time() {
const rept = [];
while (rept.length < 1) {
const selected = [];
while (selected.length < 6) {
const num = parseInt(Math.random() * 45) + 1;
if (selected.indexOf(num) == -1) {
selected.push(num);
selected.sort((a, b) => a - b)
}
}
console.log(selected)
let hasNum = false;
for (const lotto of rept) {
if (lotto == selected.toString()) {
hasNum = true;
break;
}
}
if (!hasNum) rept.push(selected);
}
console.log(rept)
document.getElementById("ran").innerHTML = rept
}
앞서 만든 6개의 중복되지 않는 임의의 숫자를 뽑는 자바스크립트 코드에서
setInterval(함수이름,시간) 을 사용해서 지정된 시간마다 숫자를 뽑는 코드를 반복해서 돌아갈수 있게 했고 이것을 html로 출력했다.
2-2. javascript 코드
var roll = null;
function start() {
if(!isStart) {
isStart = true;
time();
roll = setInterval(time, 10)
}
}
function stop() {
if (roll != null) {
clearInterval(roll);
isStart = false;
}
}
</script>
여기서는 setInterval 함수가 실행 또는 중지될 수 있도록 제어하기 위한 코드이다.
처음 코딩을 했을 때 시작 버튼을 1번만 누르고 중지버튼을 누르면 정상 작동 했지만, 시작 버튼을 2번 이상 누르면 숫자가 갱신되는 속도가 빨라지고 중지버튼이 먹통이 되는 버그가 있었다.
이 문제를 해결하기 위해 script코드 1번째 줄에 isstart=false 라는 선언을 한 뒤 if(!start)로 초기값은 false로 만들지만 버튼이 눌리면 true로 바뀌며 시작 버튼이 중첩되어 실행되지 않도록 만들었다.
3.css 코드
<style>
.rollbutton {
height: 50px;
background-color: whitesmoke;
width: fit-content;
margin: auto;
/* margin-top: 12%; */
border-radius: 5px;
}
.rollbutton>input {
width: 150px;
height: 40px;
border-radius: 5px;
}
.ran {
margin: 0% 0% 0% 0%;
width: 100%;
height: 450px;
/* border: 1px solid black; */
background-color: whitesmoke;
}
h3 {
text-align: center;
text-decoration: none;
font-size: 80px;
}
.tit {
font-size: 80px;
height: 130px;
width: 100%;
color: black;
background-color: whitesmoke;
border-radius: 8px;
border: none;
}
</style>
필요에 따라 수정해서 쓰면 된다.