startit/oppgaver/uke7/reaksjonstid/mvc.js

82 lines
2.3 KiB
JavaScript
Raw Normal View History

2024-09-18 12:20:01 +02:00
2024-09-17 14:35:16 +02:00
// model
var app = document.getElementById('app');
var html = ' ';
var lampArray = [];
2024-09-18 12:20:01 +02:00
var selectedLampIndex = 0;
2024-09-17 14:35:16 +02:00
var lightOn;
2024-09-18 12:20:01 +02:00
var clickLamp = document.getElementById('selectedLampIndex')
var startTime = new Date().getTime();
var finishTime = new Date().getTime();
var spentMilliseconds = Math.floor(finishTime - startTime);
var spentSeconds = spentMilliseconds / 1000;
2024-09-17 14:35:16 +02:00
// view
updateView();
twentyFive();
lightUpRandomLamp();
function updateView() {
2024-09-18 12:20:01 +02:00
app.innerHTML = html + /*HTML*/` <h2>Klikk på en lampe for å skifte</h2><div id="showTime">timeSpent</div>`;
2024-09-17 14:35:16 +02:00
}
// controller
function twentyFive() {
lampArray = [];
let lamp = 0;
for (i = 0; i < 25; i++) {
html += /*HTML*/ `
<div class="circles" id="${lamp}"></div>
`;
lampArray.push(lamp)
lamp++;
}
updateView();
}
function lightUpRandomLamp() {
checkForLightOn();
let divToReplace = ' ';
2024-09-18 12:20:01 +02:00
selectedLampIndex = Math.floor(Math.random() * lampArray.length);
2024-09-17 14:35:16 +02:00
divToReplace = document.getElementById(selectedLampIndex);
let divToreplaceWith = document.getElementById(selectedLampIndex).classList = `circles lightOn`
2024-09-18 12:20:01 +02:00
html = html.replace(divToReplace, divToreplaceWith)
setOnClick = document.getElementById(selectedLampIndex).onclick = lightUpRandomLamp;
startTimer();
html = html + setOnClick
2024-09-17 14:35:16 +02:00
clearScreen();
2024-09-18 12:20:01 +02:00
2024-09-17 14:35:16 +02:00
}
function clearScreen() {
html = '';
}
function checkForLightOn() {
for (i = 0; i < lampArray.length; i++) {
document.getElementById(i).classList.contains('circles')
2024-09-18 12:20:01 +02:00
if (document.getElementById(i).classList.contains("lightOn")) {
document.getElementById(i).classList = `circles`;
2024-09-17 14:35:16 +02:00
}
}
2024-09-18 12:20:01 +02:00
}
function startTimer() {
clickLamp.addEventListener("click", stopTimer)
var currentTime = new Date().getTime();
let timeSpent = Math.floor(currentTime - startTime)
let timeSpentSeconds = (timeSpent / 1000)
console.log(timeSpentSeconds)
}
function stopTimer() {
document.getElementById(selectedLampIndex).removeEventListener("click", stopTimer)
var currentTime = new Date().getTime();
let timeSpent2 = Math.floor(currentTime - startTime)
newTime = (timeSpent2 / 1000)
console.log(newTime);
document.getElementById(selectedLampIndex).addEventListener("click", startTimer)
}