Skip to content

Commit

Permalink
docs: javascript gameloop post with code editor
Browse files Browse the repository at this point in the history
  • Loading branch information
ashfidable committed Aug 31, 2024
1 parent 1a901c9 commit 1e89a1a
Showing 1 changed file with 98 additions and 1 deletion.
99 changes: 98 additions & 1 deletion src/content/posts/snippets/javascript-gameloop.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ tags:
---

import CodeTabs from '$components/tabs/code-tabs.astro'
import CodeEditor from '$components/code-editor/code-editor.svelte'



## Overview
This snippet provides a game loop in **JavaScript** and **TypeScript** that runs every frame, ensuring more consistent values. It's a basic snippet that can be modified later to include additional functionalities, such as handling tab switching (*as JavaScript is throttled when a tab is switched*).
Expand Down Expand Up @@ -105,4 +108,98 @@ This snippet provides a game loop in **JavaScript** and **TypeScript** that runs
requestAnimationFrame(gameLoop);
```
</Fragment>
</CodeTabs>
</CodeTabs>


## Code Editor


<CodeEditor
title="Counter Increment"
baseHtml={`
<p>
Click the button below to start the <span>Timer.</span>
</p>
<em>Check the JavaScript Tab to see the logic.</em>
<button>Click to Start</button>
`}
baseStyles={`
/* Base Styles - you are free to edit them or yoink, it's only for PRESENTATION PURPOSE */
body {
font-family: system-ui;
color: white;
background: #262434;
/* Centering */
display: grid;
justify-items: center;
align-items: center;
}
/* Paragraph Styles */
p {
font-weight: bold;
font-size: 1rem;
text-align: center;
}
/* Gradient Button Styles */
button {
cursor: pointer;
color: #c8a9ef;
font-family: inherit;
font-size: 1rem;
border: 0;
border-radius: 0.5rem;
padding: 1rem;
margin-top: 1rem;
background: #8e2de2;
background: linear-gradient(to bottom left, #4a00e0, #8e2de2);
background-size: 200%;
transition:
background-size 250ms linear,
color 250ms linear,
transform 75ms linear;
}
button:hover {
background-size: 100%;
color: white;
transform: scale(1.1);
}
`}
baseScript={`
// Variables that we will change and keep track of in countdown timer
let isPlaying = false;
let counter = 0;
// References of DOM Elements
const playButton = document.querySelector("button");
const paragraph = document.querySelector("p");
// Toggle true or false
playButton.addEventListener("click", () => (isPlaying = !isPlaying));
let lastTime = 0;
let deltaTime = 0;
function gameLoop(currentTime) {
deltaTime = (currentTime - lastTime) / 1000;
lastTime = currentTime;
update(deltaTime);
render();
requestAnimationFrame(gameLoop);
}
function update(deltaTime) {
if (isPlaying) {
counter += 1;
paragraph.innerHTML = counter;
}
}
function render() {}
// Start Loop
requestAnimationFrame(gameLoop);
`}
client:idle />

0 comments on commit 1e89a1a

Please sign in to comment.