Best JavaScript code snippet using wpt
script.js
Source:script.js
1var WindowforQuestions = document.getElementById("questionWindow");2var WindowforChoices = document.getElementById("choicesWindow");3var WindowforResult = document.getElementById("resultsWindow");4var WindowforHighScore = document.getElementById("highScoreWindow")5var startButton = document.getElementById("btn-start");6var chosenQuestion = {};7var timer;8var answeredCounter;9var timeInterval;10var highScoreList = [];11var highScoreListInString = [];12var scoreListPointer;13var myEraser;14// Event Listeners on click15document.getElementById('highScoreWindow').addEventListener('click', displayHighScore);16document.getElementById("btn-start").addEventListener("click", startGame);17// This is the main function18function startGame() {19 // Disable to display of high scores immediately.20 document.getElementById('highScoreWindow').removeEventListener('click', displayHighScore);21 answeredCounter = 0;22 timer = 40;23 clearAllDisplay();24 startTimer();25 refreshQuestions();26 checkAnswer();27}28// Pointer for the value of timer remaining29var countdownTimer = document.getElementById("timeRemaining");30// This is the timer function31function startTimer() {32 timeInterval = setInterval(function () {33 if (timer > 0) {34 // display the decrement every second35 countdownTimer.textContent = timer + " sec(s)";36 timer--;37 }38 else {39 //stop the setInteval function once the timer runs out.40 countdownTimer.textContent = timer + " sec(s)";41 clearInterval(timeInterval);42 displayHighScore();43 }44 }, 1000);45}46// Randomnly pick a question obj from the list47function pickRandomQuestion() {48 var tempChosenQuestion = QuestionList[Math.floor(Math.random(QuestionList) * QuestionList.length)];49 // This is to make sure that a question is not displayed twice in a row.50 while (tempChosenQuestion == chosenQuestion) {51 var tempChosenQuestion = QuestionList[Math.floor(Math.random(QuestionList) * QuestionList.length)];52 }53 chosenQuestion = tempChosenQuestion;54}55function displayQuestion() {56 WindowforQuestions.classList.add("questionText");57 WindowforQuestions.innerHTML = chosenQuestion.question;58}59function displayChoices() {60 for (var x = 1; x <= 4; x++) {61 var button = document.createElement("button");62 button.innerHTML = chosenQuestion["choice" + x];63 button.classList.add("btn-choices");64 WindowforChoices.appendChild(button);65 }66}67function checkAnswer() {68 WindowforChoices.addEventListener("click", function (event) {69 var selectedButton = event.target70 if (selectedButton.matches(".btn-choices")) {71 event.preventDefault();72 var selectedAnswer = selectedButton.innerHTML73 answeredCounter++;74 if (answeredCounter < 5) {75 // If the answer is wrong.76 if (selectedAnswer != chosenQuestion.answer) {77 timer = timer - 10;78 countdownTimer.textContent = timer + " sec(s)";79 displayResult(selectedAnswer);80 refreshQuestions();81 // Executes when a wrong answer make the timer less than or equal to zero.82 if (timer < 0) {83 84 timer = 0;85 countdownTimer.textContent = timer + " sec(s)";86 clearInterval(timeInterval); //TURN INTO A COMMENT IF ZERO SCORE ARE NOT TO BE RECORD87 enterHighScore(); //TURN INTO A COMMENT IF ZERO SCORE ARE NOT TO BE RECORD88 /* REMOVE COMMENT TAGS IF ZERO SCORES ARE NOT TO BE RECORD89 alert("Your score is 0.")90 document.getElementById('highScoreWindow').addEventListener('click', displayHighScore);91 displayHighScore(); */92 }93 }94 // If the answer is correct95 else {96 displayResult(selectedAnswer);97 refreshQuestions();98 }99 }100 else {101 clearInterval(timeInterval);102 countdownTimer.textContent = timer + " sec(s)";103 104 enterHighScore();105 }106 }107 });108}109// Display a prompt on screen if answer is right or wrong.110function displayResult(selectedAnswer) {111 if (selectedAnswer != chosenQuestion.answer) { // Display: Says answer is correct112 WindowforResult.innerHTML = 'The answer is INCORRECT!';113 WindowforResult.style.color = 'red';114 115 }116 else { // Display: Says answer is correct117 WindowforResult.innerHTML = 'CORRECT!';118 WindowforResult.style.color = 'green';119 120 }121 myEraser = setTimeout(deleteResultWindowContent, 1000); // Erases the result after 1 sec.122}123function enterHighScore() {124 clearAllDisplay();125 // Add event listener on keypress126 document.addEventListener('keypress', (event) => { var keyName = event.key; var keyCode = event.code; }, false);127 //Display message All Done!!!128 WindowforQuestions.innerHTML = "All done!!!";129 // Displaying the score130 WindowforChoices.innerHTML = "Your score is: " + timer;131 WindowforChoices.classList.add("choicesWindow-Saving");132 WindowforResult.setAttribute("style", "flex-direction: row");133 // Make the input box label134 WindowforResult.classList.add("resultsWindow-Saving");135 var lblInputInitials = document.createElement("label");136 lblInputInitials.setAttribute("id", "input-label");137 lblInputInitials.innerHTML = "Enter initials: "138 lblInputInitials.setAttribute('style', 'margin-left: 10px margin-right: 10px');139 WindowforResult.appendChild(lblInputInitials);140 // Make the input box141 var inputInitials = document.createElement("input");142 inputInitials.setAttribute("id", "initialInput");143 inputInitials.setAttribute("for", "initialInput")144 inputInitials.setAttribute('type', 'text');145 inputInitials.setAttribute('value', '');146 inputInitials.setAttribute('style', 'margin-left: 10px margin-right: 10px');147 WindowforResult.appendChild(inputInitials);148 // Create the submit button149 var submitButton = document.createElement("input");150 submitButton.setAttribute("id", "submit-btn");151 submitButton.setAttribute("type", "submit");152 submitButton.setAttribute("value", "Submit");153 submitButton.setAttribute('style', 'margin-left: 10px margin-right: 10px');154 WindowforResult.appendChild(submitButton);155 // Add event listener on click for Submit button156 document.getElementById("submit-btn").addEventListener("click", saveScore);157 // Add event listener on keypress for Enter 158 document.addEventListener('keypress', (event) => {159 var keyName = event.key;160 if (keyName == 'Enter') {161 saveScore();162 }163 }, false);164}165function saveScore() {166 // Disable event listeners for keyboard entry167 document.removeEventListener('keypress', () => { }, false);168 // Converts initial to uppercase letters.169 var enteredInit = (document.getElementById("initialInput").value).toUpperCase();170 // Prepares a container for player initials/name and score171 var objScore = {172 Init: enteredInit,173 Score: timer174 };175 // Save the entry if the input box is not empty176 if (enteredInit) {177 // Retrieving the local storage data178 var tempStringList = localStorage.getItem("list");179 // If the local storage is not empty then update highScoreList180 if (tempStringList) {181 highScoreList = JSON.parse(tempStringList);182 }183 highScoreList.push(objScore); // Adding the new highscore unto the high score list184 //Sorting the high scores from highest to lowest185 highScoreList.sort((a, b) => { return b.Score - a.Score; });186 // Saving a string file into the local storage187 localStorage.setItem("list", JSON.stringify(highScoreList));188 displayHighScore();189 }190 else {191 // Prompt: Input is blank192 alert("Please enter your initials!");193 }194}195// Displays the HIGH SCORES list196function displayHighScore() {197 document.getElementById('highScoreWindow').addEventListener('click', displayHighScore);198 clearAllDisplay(); 199 countdownTimer.innerHTML = "";200 if (localStorage.length) { // Tests if the localStorage is empty or not.201 var tempStringList = localStorage.getItem("list");202 highScoreList = JSON.parse(tempStringList);203 WindowforQuestions.innerHTML = "HIGH SCORES";204 // Creates the list in accordance to content of local storage of HIGH SCORES205 for (x = 0; x < highScoreList.length; x++) {206 var listSpan = document.createElement("span");207 listSpan.setAttribute("style", "padding: 5px; width: 50%; margin: 2px");208 listSpan.style.backgroundColor = "cornflowerblue";209 listSpan.style.borderRadius = "5px";210 listSpan.innerHTML = x + 1 + ". " + highScoreList[x].Init + " - " + highScoreList[x].Score;211 WindowforChoices.style.textAlign = "left";212 WindowforChoices.style.position = "relative";213 WindowforChoices.style.display = "flex";214 WindowforChoices.style.alignItems = "center";215 WindowforChoices.style.left = "25%";216 WindowforChoices.style.width = "50%";217 WindowforChoices.appendChild(listSpan);218 }219 }220 displayOptions() // This will display buttons to RESTART or CLEAR high scores.221}222// This will display buttons to restart or clear high scores.223function displayOptions() {224 // Displays a title - not a sematic element of header type225 WindowforQuestions.innerHTML = "HIGH SCORES";226 WindowforQuestions.style.fontSize = '2em';227 // Creates a button for the game RESTART button228 var btn = document.createElement("button");229 WindowforResult.appendChild(btn);230 btn.setAttribute("id", "btn-start");231 btn.setAttribute("class", "btn-start");232 btn.innerHTML = "RESTART";233 var restartButton = document.getElementById("btn-start");234 //document.getElementById("btn-start").addEventListener("click", restartGame);235 restartButton.addEventListener("click", restartGame);236 // Creates a button to clear high scores record.237 var clearBtn = document.createElement("button");238 WindowforResult.appendChild(clearBtn);239 clearBtn.setAttribute("id", "btn-clearHighScore");240 clearBtn.setAttribute("class", "btn-start");241 clearBtn.innerHTML = "CLEAR";242 var clearButton = document.getElementById("btn-clearHighScore");243 //document.getElementById("btn-clearHighScore").addEventListener('click', clearHighScores);244 clearButton.addEventListener('click', clearHighScores);245}246// Clears the High Score localStorage and displays the updated list247function clearHighScores() {248 localStorage.clear();249 displayHighScore();250}251// This reloads the page if restart button is chose.252function restartGame() {253 window.location.reload()254}255// Display the first and succeeding questions256function refreshQuestions() {257 clearForNextQuestion();258 pickRandomQuestion();259 displayQuestion();260 displayChoices();261}262// Functions to Delete CONTENTS OR DISPLAY - Does not delete the elements.263function clearAllDisplay() {264 clearForNextQuestion()265 while (WindowforResult.firstChild) {266 WindowforResult.removeChild(WindowforResult.firstChild);267 }268 document.getElementById('footer').innerHTML = '';269}270// Clearing display for the next question (#questionWindow and #choicesWindow).271function clearForNextQuestion() {272 while (WindowforQuestions.firstChild) {273 WindowforQuestions.removeChild(WindowforQuestions.firstChild);274 }275 while (WindowforChoices.firstChild) {276 WindowforChoices.removeChild(WindowforChoices.firstChild);277 }278}279// Clear content for #resultsWindow280function deleteResultWindowContent() {281 if (answeredCounter < 5 && timer != 0) { // Condition prevents unexpected deletion.282 while (WindowforResult.firstChild) {283 WindowforResult.removeChild(WindowforResult.firstChild);284 }285 }...
browser.js
Source:browser.js
1"use strict";2const { windows, isBrowser, isInteractive, isDocumentLoaded,3 getOuterId } = require("../window/utils");4const { InputPort } = require("./system");5const { lift, merges, foldp, keepIf, start, Input } = require("../event/utils");6const { patch } = require("diffpatcher/index");7const { Sequence, seq, filter, object, pairs } = require("../util/sequence");8const opened = seq(function*() {9 const items = windows("navigator:browser", {includePrivates: true});10 for (let item of items) {11 yield [getOuterId(item), item];12 }13});14const interactive = filter(([_, window]) => isInteractive(window), opened);15const loaded = filter(([_, window]) => isDocumentLoaded(window), opened);16const Update = window => window && object([getOuterId(window), window]);17const Delete = window => window && object([getOuterId(window), null]);18const LastClosed = lift(Delete,19 keepIf(isBrowser, null,20 new InputPort({topic: "domwindowclosed"})));21exports.LastClosed = LastClosed;22const windowFor = document => document && document.defaultView;23const InteractiveDoc = new InputPort({topic: "chrome-document-interactive"});24const InteractiveWin = lift(windowFor, InteractiveDoc);25const LastInteractive = lift(Update, keepIf(isBrowser, null, InteractiveWin));26exports.LastInteractive = LastInteractive;27const LoadedDoc = new InputPort({topic: "chrome-document-loaded"});28const LoadedWin = lift(windowFor, LoadedDoc);29const LastLoaded = lift(Update, keepIf(isBrowser, null, LoadedWin));30exports.LastLoaded = LastLoaded;31const initialize = input => {32 if (!input.initialized) {33 input.value = object(...input.value);34 Input.start(input);35 input.initialized = true;36 }37};38const Interactive = foldp(patch, interactive, merges([LastInteractive,39 LastClosed]));40Interactive[start] = initialize;41exports.Interactive = Interactive;42const Loaded = foldp(patch, loaded, merges([LastLoaded, LastClosed]));43Loaded[start] = initialize;...
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) return console.error(err);4 wpt.getTestResults(data.data.testId, function(err, data) {5 if (err) return console.error(err);6 console.log(data.data.median.firstView.loadTime);7 console.log(data.data.median.firstView.SpeedIndex);8 console.log(data.data.median.firstView.TTFB);9 console.log(data.data.median.firstView.render);10 console.log(data.data.median.firstView.fullyLoaded);11 console.log(data.data.median.firstView.docTime);12 console.log(data.data.median.firstView.domTime);13 console.log(data.data.median.firstView.score_cache);14 console.log(data.data.median.firstView.score_cdn);15 console.log(data.data.median.firstView.score_gzip);16 console.log(data.data.median.firstView.score_cookies);17 console.log(data.data.median.firstView.score_keep-alive);18 console.log(data.data.median.firstView.score_minify);19 console.log(data.data.median.firstView.score_combine);20 console.log(data.data.median.firstView.score_compress);21 console.log(data.data.median.firstView.score_etags);22 console.log(data.data.median.firstView.score_progressive_jpeg);23 console.log(data.data.median.firstView.pageSpeedVersion);24 console.log(data.data.median.firstView.titleTime);25 console.log(data.data.median.firstView.firstPaint);26 console.log(data.data.median.firstView.browser_name);27 console.log(data.data.median.firstView.browser_version);28 console.log(data.data.median.firstView.browser_process_count);29 console.log(data.data.median.firstView.browser_main_memory_kb);30 console.log(data.data.median.firstView.browser_working_set_kb);31 console.log(data.data.median.firstView.browser_other_private_memory_kb);32 console.log(data.data.median.firstView.browser_shared_memory_kb);33 console.log(data.data.median.firstView.browser_cache_memory_kb);34 console.log(data.data.median.firstView.browser_gpu_memory_kb);35 console.log(data.data.median.firstView.browser_renderer_memory_kb);36 console.log(data.data.median.firstView.browser_extension_memory_kb);37 console.log(data.data.median.firstView.browser_other_memory_kb);38 console.log(data.data.median.firstView.browser_total_private_memory_kb);39 console.log(data.data.median.firstView.browser_total_virtual_memory_kb);40 console.log(data.data.median.firstView
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.getLocations(function(err, data) {4 if (err) return console.error(err);5 console.log(data);6});7}, function(err, data) {8 if (err) return console.error(err);9 console.log(data);10 wpt.getTestResults(data.data.testId, function(err, data) {11 if (err) return console.error(err);12 console.log(data);13 });14});15}, function(err, data) {16 if (err) return console.error(err);17 console.log(data);18 wpt.getTestResults(data.data.testId, function(err, data) {19 if (err) return console.error(err);20 console.log(data);21 });22});23}, function(err, data) {24 if (err) return console.error(err);25 console.log(data);26 wpt.getTestResults(data.data.testId, function(err, data) {27 if (err) return console.error(err);28 console.log(data);29 });30});31}, function(err, data) {32 if (err) return console.error(err);33 console.log(data);34 wpt.getTestResults(data.data.testId, function(err, data) {35 if (err) return console.error(err);36 console.log(data);37 });38});
Using AI Code Generation
1var win = require('wptoolkit').windowFor({2});3win.focus();4var win = require('wptoolkit').windowFor({5});6win.focus();
Using AI Code Generation
1function test() {2 var win = window.open("about:blank", "test");3 var frame = win.document.createElement("iframe");4 frame.setAttribute("name", "frame");5 win.document.body.appendChild(frame);6 var frameDoc = frame.contentWindow.document;7 frameDoc.open();8 frameDoc.write("<html><head></head><body>test</body></html>");9 frameDoc.close();10 var frameWin = windowFor("frame", win);11 is(frameWin, frame.contentWindow, "windowFor returns the correct window");12 win.close();13 finish();14}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!