Custom javascript Video player stops after 11 seconds - javascript

I am currently developing a custom javascript videoplayer for my website to be able to show some showreels. It works perfectly fine in firefox but in chrome the demo video stops everytime after 11 seconds but the buffering process has already loaded more than 11s.
Here is the link to the videoplayer: https://www.cankarka.com/en/portfolio
Does anyone have an idea why this is happening? I got no errors in the console.
Thanks in advance :)
This is my HTML:
<div class="custom-video-player">
<video class="video" src="inc/video.mp4" preload="auto"></video>
<div class="video-controls">
<div class="video-bar">
<div id="currentBuffer" class="currentBuffer"></div>
<div id="currentProcess" class="currentProcess"></div>
</div>
<div class="buttons">
<button id="skip-back" class="skipBack" type="button"></button>
<button id="playPause" type="button"></button>
<button id="skip-front" class="skipForward" type="button"></button>
<button id="volumeBtn" class="volumeHigh" type="button"></button>
<div class="volume-slider-container">
<div class="volume-slider-container-inner">
<div id="volume-slider" class="volume-slider"></div>
</div>
</div>
<div class="volume-slider-range"></div>
<div class="videoTimer-container">
<span id="videoCurrentTime" class="videoTimer"></span> <span id="slash" class="videoTimer">/</span> <span id="videoTime" class="videoTimer"></span>
</div>
<button id="fullscreenToggle" class="fullscreen" type="button"></button>
</div>
</div>
</div>
This is my javascript code:
function initializeVideoPlayer()
{
var videoPlayers = document.querySelectorAll('.custom-video-player');
for (var i = 0; i < videoPlayers.length; ++i)
{
initControls(videoPlayers[i]);
}
}
function initControls(videoPlayerContainer)
{
var video = videoPlayerContainer.querySelector('.video');
var videoBarContainer = videoPlayerContainer.querySelector('.video-bar');
video.onerror = function()
{
console.log("Error: " + video.error.code);
};
// Timelines
var currentProcess = videoPlayerContainer.querySelector("div.currentProcess");
var currentBuffer = videoPlayerContainer.querySelector("div.currentBuffer");
// Buttons
var playPauseBtn = videoPlayerContainer.querySelector('#playPause');
video.addEventListener('timeupdate', updateTimeline);
video.addEventListener('click', togglePlayPause);
video.addEventListener('progress', updateBuffer);
playPauseBtn.addEventListener('click', togglePlayPause);
skipBackward.addEventListener('click', skipBackwardFunction);
skipForward.addEventListener('click', skipForwardFunction);
volumeBtn.addEventListener('click', setVolumeByBtn);
let mouseDown = false;
videoBarContainer.addEventListener('click', scrub);
videoBarContainer.addEventListener('mousemove', (e) => mouseDown && scrub(e));
videoBarContainer.addEventListener('mousedown', () => mouseDown = true);
videoBarContainer.addEventListener('mouseup', () => mouseDown = false);
function scrub(e)
{
var scrubTime = (e.offsetX / videoBarContainer.offsetWidth) * video.duration;
video.currentTime = scrubTime;
}
function skipForwardFunction()
{
video.currentTime += skipTime;
}
function skipBackwardFunction()
{
video.currentTime -= skipTime;
}
function updateBuffer()
{
var duration = video.duration;
if (duration > 0)
{
for (var i = 0; i < video.buffered.length; ++i)
{
if (video.buffered.start(video.buffered.length - 1 - i) < video.currentTime)
{
currentBuffer.style.width = (video.buffered.end(video.buffered.length - 1 - i) / duration) * 100 + "%";
break;
}
}
}
}
function updateTimeline()
{
// Timeline updaten
var percent = (video.currentTime / video.duration) * 100;
currentProcess.style.width = percent + "%";
// Aktuelle Zeit anzeigen
var min = Math.floor(video.currentTime / 60);
var sec = Math.floor(video.currentTime - min * 60);
if (sec < 10)
{
sec = "0" + sec;
}
if (min < 10)
{
min = "0" + min;
}
if (min >= 60 && min < 120)
{
min = "01:" + (min - 60);
}
else if (min >= 120 && min < 180)
{
min = "02:" + (min - 120);
}
else if (min >= 180 && min < 240)
{
min = "03:" + (min - 180);
}
else if (min >= 240 && min < 300)
{
min = "04:" + (min - 240);
}
else if (min >= 300 && min < 360)
{
min = "05:" + (min - 300);
}
else
{
min = "00:" + min;
}
// Gesamte Zeit berechnen
var minTotal = Math.floor(video.duration / 60);
var secTotal = Math.floor(video.duration - minTotal * 60);
if (secTotal < 10)
{
secTotal = "0" + secTotal;
}
if (minTotal < 10)
{
minTotal = "0" + minTotal;
}
if (minTotal >= 60 && minTotal < 120)
{
minTotal = "01:" + (minTotal - 60);
}
else if (minTotal >= 120 && minTotal < 180)
{
minTotal = "02:" + (minTotal - 120);
}
else if (minTotal >= 180 && minTotal < 240)
{
minTotal = "03:" + (minTotal - 180);
}
else if (minTotal >= 240 && minTotal < 300)
{
minTotal = "04:" + (minTotal - 240);
}
else if (minTotal >= 300 && minTotal < 360)
{
minTotal = "05:" + (minTotal - 300);
}
else
{
minTotal = "00:" + minTotal;
}
videoCurrentTime.innerHTML = min + ":" + sec;
videoTime.innerHTML = minTotal + ":" + secTotal;
if (video.ended)
{
playPauseBtn.className = "play";
}
}
function togglePlayPause()
{
if (video.paused)
{
playVideo();
}
else
{
playPauseBtn.className = "play";
video.pause();
}
}
function playVideo()
{
var playPromise = video.play();
if (playPromise !== undefined)
{
playPromise.then(_ => {
// Video started successfully
playPauseBtn.className = "pause";
}).catch(error => {
// Video was interrupted
playPauseBtn.className = "play";
});
}
}
}
window.onload = initializeVideoPlayer;

In order to debug the video, you can use this code:
const videoElement = document.getElementsByTagName('video')[0];
const b = HTMLMediaElement.prototype;
const allNames = new Set();
for (let o = b; o != Object.prototype; o = Object.getPrototypeOf(o)) {
for (let name of Object.getOwnPropertyNames(o)) {
allNames.add(name);
}
}
const array = Array.from(allNames).filter(x => /^on/.test(x)).map(x => x.substring(2));
array.forEach(x => videoElement.addEventListener(x, console.log));
This shows that an Event of type error occurs, followed by timeupdate and then pause.
To get the actual error, use videoElement.error which shows the following:
{
code: 3,
message: "PIPELINE_ERROR_DECODE: Failed to send audio packet for decoding: {timestamp=12176542 duration=21250 size=516 is_key_frame=1 encrypted=0}"
}
That means your file is corrupted, try to encode it in a different way. Also, maybe this answer will help: Audio playback halts/stops on Chrome 64

Related

I am having an issue redrawing some circles onto my html canvas

I am using a basic html canvas to create a simple game using javascript, but I am having an issue while trying to redraw my window. I have created a redraw_window function that I call whenever i want a new frame to show on the screen, but when I try to call the redraw_window function from this location on line 151, it does not work. The screen does not update. Any ideas why?
const c = canvas.getContext("2d")
canvas.width = innerWidth
canvas.height = innerHeight
const random = (min, max) => Math.floor(Math.random() * (max - min)) + min;
class Light {
constructor(pos,vel){
this.pos = pos
this.vel = vel
}
move(){
if (this.pos == 0){
this.vel = 1
}
if(this.pos == 9){
this.vel = -1
}
this.pos += this.vel
}
}
function is_not_in(val,list){
for (var i = 0; i < list.length; i++){
if (list[i] == val){
return false
}
}
return true
}
function clear_window(){
c.clearRect(0,0,canvas.width,canvas.height)
}
function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
function redraw_window(pos){
c.font = "80px serif"
//let board = [1,1,1,1,1,1,1,1,1,1]
positions = [canvas.width/2-450,canvas.width/2-350,canvas.width/2-250,canvas.width/2-150,canvas.width/2-50,canvas.width/2+50,canvas.width/2+150,canvas.width/2+250,canvas.width/2+350,canvas.width/2+450,]
//board[light.pos] = 0
clear_window()
c.fillStyle = "black"
//c.fillText(board.toString(),canvas.width/2-c.measureText(board.toString()).width/2,canvas.height/2)
//c.fillText("Troy likes big hairy black balls",canvas.width/2-c.measureText("Troy likes big hairy black balls").width/2,canvas.height/2+80)
for (var i = 0; i < positions.length; i++) {
let radius = 20
if (pos != i){
c.beginPath()
c.arc(positions[i],canvas.height/2,radius,0,Math.PI * 2,false)
c.fillStyle = "black"
c.fill()
}
if (pos == i){
c.beginPath()
c.arc(positions[i],canvas.height/2,radius,0,Math.PI * 2,false)
c.fillStyle = "green"
c.fill()
}
}
}
function choose(choices) {
var index = Math.floor(Math.random() * choices.length);
return choices[index];
}
function win_animation(){
redraw_window(null)
sleep(300)
redraw_window(light.pos)
sleep(300)
redraw_window(null)
sleep(300)
redraw_window(light.pos)
}
var light = new Light(random(0,9),choose([-1,1]))
function main(){
var FPS = 60
var SPEED = 0.5
var COOLDOWN = FPS * 0.25
var SCORE_TO_WIN = 5
var right_player_points = 0
var left_player_points = 0
var frame = 0
var right_player_cooldown = 0
var left_player_cooldown = 0
var keys_pressed = []
var right_player_key = "ShiftRight"
var left_player_key = "ShiftLeft"
var right_player_cooldown = 0
var left_player_cooldown = 0
var playing = true
//handles cooldown and keys pressed list
window.addEventListener("keydown",(event)=>{
if (event.code == right_player_key && is_not_in(right_player_key,keys_pressed)){
if (right_player_cooldown == 0){
right_player_cooldown = COOLDOWN
keys_pressed.push(event.code)
}
}
if (event.code == left_player_key && is_not_in(left_player_key,keys_pressed)){
if (left_player_cooldown == 0){
left_player_cooldown = COOLDOWN
keys_pressed.push(event.code)
}
}
})
//runs fps times per second
var run = setInterval(run,1000 / FPS)
function run(){
frame += 1
if (left_player_cooldown > 0){
left_player_cooldown -= 1
}
if (right_player_cooldown > 0){
right_player_cooldown -= 1
}
//runs SPEED times per second
if (frame >= FPS * SPEED){
frame = 0
if (!is_not_in(right_player_key,keys_pressed) && light.pos == 9){
right_player_points += 1
**VVV THIS IS WHERE I AM HAVING MY ISSUE VVV**
redraw_window(null);
alert("right player:" + right_player_points.toString())
if (right_player_points >= SCORE_TO_WIN){
alert("right player Wins")
right_player_points = 0
left_player_points = 0
light = new Light(random(0,9),choose([-1,1]))
}
}
if (!is_not_in(left_player_key,keys_pressed) && light.pos == 0){
left_player_points += 1
light = new Light(random(0,9),choose([-1,1]))
alert("left player:" + left_player_points.toString())
if (left_player_points >= SCORE_TO_WIN){
alert("left player wins")
left_player_points = 0
right_player_points = 0
}
}
light.move()
redraw_window(light.pos)
keys_pressed = []
}
}
}
main() ```
The main issue I can see here is that you have a variable and a function both named run. The setInterval call is being overwritten with the function definition. I recommend you rename the variable run to runInterval.
Change
var run = setInterval(run, 1000 / FPS)
to
var runInterval = setInterval(run, 1000 / FPS)
See if that helps.

Collision detection not working (Javascript)

I'm trying to build a simple game and having hard time with collision detecting. I want the alert to be popped up when the hero hits the virus and below is my js code. I'm not sure if my collision detect logic is wrong too. The viruses are moving randomly and I used CSS transition for them to move gradually.
var henryLocation = {
top: 700,
left: 700
}
document.onkeydown = function (evt) {
// console.log(evt)
if (evt.keyCode === 38 && henryLocation.top > 10) {
henryLocation.top = henryLocation.top - 25
} else if (evt.keyCode === 40 && henryLocation.top < 700) {
henryLocation.top = henryLocation.top + 25
} else if (evt.keyCode === 37 && henryLocation.left > 10) {
henryLocation.left = henryLocation.left - 25
} else if (evt.keyCode === 39 && henryLocation.left < 1360) {
henryLocation.left = henryLocation.left + 25
}
moveHenry()
}
function moveHenry () {
document.getElementById('henry').style.top = henryLocation.top + 'px'
document.getElementById('henry').style.left = henryLocation.left + 'px'
}
const startBtn = document.getElementById('btn-start')
startBtn.addEventListener("click", theGame)
function theGame () {
const startGame = setInterval(moveCorona, 1300)
function moveCorona () {
const theCorona = document.getElementById('corona')
const theCorona1 = document.getElementById('corona1')
const theCorona2 = document.getElementById('corona2')
const w = 1300, h = 600
theCorona.style.top = Math.floor(Math.random() * h) + 'px'
theCorona.style.left = Math.floor(Math.random() * w) + 'px'
theCorona1.style.top = Math.floor(Math.random() * h) + 'px'
theCorona1.style.left = Math.floor(Math.random() * w) + 'px'
theCorona2.style.top = Math.floor(Math.random() * h) + 'px'
theCorona2.style.left = Math.floor(Math.random() * w) + 'px'
function collisionDetect () {
var theHenry = henry.getBoundingClientRect();
var theCorona = corona.getBoundingClientRect();
if ((theCorona.top > theHenry.top && theCorona.top < theHenry.bottom) || (theCorona.bottom > theHenry.top && theCorona.bottom < theHenry.bottom)) {
let verticalCollision = true
} else {
let verticalCollision = false
}
if ((theCorona.right > theHenry.left && theCorona.right < theHenry.right) || (theCorona.left < theHenry.right && theCorona.left > theHenry.left)) {
let horizontalCollision = true
} else {
let horizontalCollision = false
}
if (verticalCollision && horizontalCollision) {
alert('collision detected')
} else {
console.log('Game goes on')
}
}
// collisionDetect()
}
}
function gameLoop () {
setTimeout(gameLoop, 1000)
}
gameLoop()

How to have a setInterval not act like a for loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
So here's my stopwatch code, and it should be working awesome except when I tested it, it gave up trying to actually count time and instead counted up like it's in a for loop. You can see for yourself here:
var currTime = 0
var origTime = 0
var timerFunc
var a = document.querySelector('#node1')
var i = 0
var md
var sd
var msd
function button1Action() {
if (i === 0) {
origTime = document.getElementById("time").value
currTime = document.getElementById("time").value
var b = a.cloneNode(true)
b.id = 'node2'
b.innerHTML = '<h1 id="text"></h1><button id="button1" class="button1" onclick="button1Action()">Start</button> <button id="button2" class="button2" onclick="button2Action()">Clear</button>'
a.parentNode.replaceChild(b, a)
let hd = Math.floor(currTime / 3600000)
let m = Math.floor((currTime % 3600000) / 60000)
let s = Math.floor((currTime % 60000) / 1000)
let ms = Math.floor(currTime % 1000)
if (m < 10) {
md = `0${m}`
} else {
md = `${m}`
}
if (s < 10) {
sd = `0${s}`
} else {
sd = `${s}`
}
if (ms < 10) {
msd = `00${ms}`
} else if (ms < 100) {
msd = `0${ms}`
} else {
msd = `${ms}`
}
document.getElementById("text").innerHTML = `${hd}:${md}:${sd}.${msd}`
} else if (i >= 1 && (i % 2) == 1) {
timerFunc = setInterval(function() {
currTime += 33
let hd = Math.floor(currTime / 3600000)
let m = Math.floor((currTime % 3600000) / 60000)
let s = Math.floor((currTime % 60000) / 1000)
let ms = Math.floor(currTime % 1000)
if (m < 10) {
md = `0${m}`
} else {
md = `${m}`
}
if (s < 10) {
sd = `0${s}`
} else {
sd = `${s}`
}
if (ms < 10) {
msd = `00${ms}`
} else if (ms < 100) {
msd = `0${ms}`
} else {
msd = `${ms}`
}
document.getElementById("text").innerHTML = `${hd}:${md}:${sd}.${msd}`
}, 33)
document.getElementById("button1").innerHTML = `Pause`
document.getElementById("button1").style.backgroundColor = "#0000ff"
} else if (i >= 1 && (i % 2) == 0) {
clearInterval(timerFunc)
document.getElementById("button1").innerHTML = `Cont..`
document.getElementById("button1").style.backgroundColor = "#00ff00"
} else {
throw "Error: i must be a positive integer or 0"
}
i++
}
function button2Action() {
clearInterval(timerFunc)
currTime = origTime
let hd = Math.floor(currTime / 3600000)
let m = Math.floor((currTime % 3600000) / 60000)
let s = Math.floor((currTime % 60000) / 1000)
let ms = Math.floor(currTime % 1000)
if (m < 10) {
md = `0${m}`
} else {
md = `${m}`
}
if (s < 10) {
sd = `0${s}`
} else {
sd = `${s}`
}
if (ms < 10) {
msd = `00${ms}`
} else if (ms < 100) {
msd = `0${ms}`
} else {
msd = `${ms}`
}
document.getElementById("text").innerHTML = `${hd}:${md}:${sd}.${msd}`
document.getElementById("button1").innerHTML = `Start`
document.getElementById("button1").style.backgroundColor = "#00ff00"
i = 1
}
.button1 {
background-color: #00ff00;
color: #999999;
}
.button2 {
background-color: #ff0000;
color: #eeeeee
}
.in1::placeholder {
color: #000e;
}
<!DOCTYPE html>
<html>
<head>
<title>Stopwatch</title>
</head>
<body id="node1">
<input type="number" class="in1" id="time" placeholder="0" value="0">
<br/><br/>
<button class="button1" onclick="button1Action()">Set</button>
</body>
</html>
I don't know why this is happening. Can you please help me?
<h1>Thank you!</h1>
P.S. This might just be a playcode issue, so if you don't see anything wrong, comment down below about it and I will contact support.
The problem is that you're not parsing the input to a number. So when you do currTime += 33;, it's concatenating strings instead of adding numbers. Use parseInt() when you read the inputs into the variables.
var currTime = 0
var origTime = 0
var timerFunc
var a = document.querySelector('#node1')
var i = 0
var md
var sd
var msd
var freq = 33;
function button1Action() {
if (i === 0) {
origTime = parseInt(document.getElementById("time").value)
currTime = parseInt(document.getElementById("time").value)
var b = a.cloneNode(true)
b.id = 'node2'
b.innerHTML = '<h1 id="text"></h1><button id="button1" class="button1" onclick="button1Action()">Start</button> <button id="button2" class="button2" onclick="button2Action()">Clear</button>'
a.parentNode.replaceChild(b, a)
let hd = Math.floor(currTime / 3600000)
let m = Math.floor((currTime % 3600000) / 60000)
let s = Math.floor((currTime % 60000) / 1000)
let ms = Math.floor(currTime % 1000)
if (m < 10) {
md = `0${m}`
} else {
md = `${m}`
}
if (s < 10) {
sd = `0${s}`
} else {
sd = `${s}`
}
if (ms < 10) {
msd = `00${ms}`
} else if (ms < 100) {
msd = `0${ms}`
} else {
msd = `${ms}`
}
document.getElementById("text").innerHTML = `${hd}:${md}:${sd}.${msd}`
} else if (i >= 1 && (i % 2) == 1) {
timerFunc = setInterval(function() {
currTime += freq
let hd = Math.floor(currTime / 3600000)
let m = Math.floor((currTime % 3600000) / 60000)
let s = Math.floor((currTime % 60000) / 1000)
let ms = Math.floor(currTime % 1000)
if (m < 10) {
md = `0${m}`
} else {
md = `${m}`
}
if (s < 10) {
sd = `0${s}`
} else {
sd = `${s}`
}
if (ms < 10) {
msd = `00${ms}`
} else if (ms < 100) {
msd = `0${ms}`
} else {
msd = `${ms}`
}
document.getElementById("text").innerHTML = `${hd}:${md}:${sd}.${msd}`
}, freq)
document.getElementById("button1").innerHTML = `Pause`
document.getElementById("button1").style.backgroundColor = "#0000ff"
} else if (i >= 1 && (i % 2) == 0) {
clearInterval(timerFunc)
document.getElementById("button1").innerHTML = `Cont..`
document.getElementById("button1").style.backgroundColor = "#00ff00"
} else {
throw "Error: i must be a positive integer or 0"
}
i++
}
function button2Action() {
clearInterval(timerFunc)
currTime = origTime
let hd = Math.floor(currTime / 3600000)
let m = Math.floor((currTime % 3600000) / 60000)
let s = Math.floor((currTime % 60000) / 1000)
let ms = Math.floor(currTime % 1000)
if (m < 10) {
md = `0${m}`
} else {
md = `${m}`
}
if (s < 10) {
sd = `0${s}`
} else {
sd = `${s}`
}
if (ms < 10) {
msd = `00${ms}`
} else if (ms < 100) {
msd = `0${ms}`
} else {
msd = `${ms}`
}
document.getElementById("text").innerHTML = `${hd}:${md}:${sd}.${msd}`
document.getElementById("button1").innerHTML = `Start`
document.getElementById("button1").style.backgroundColor = "#00ff00"
i = 1
}
.button1 {
background-color: #00ff00;
color: #999999;
}
.button2 {
background-color: #ff0000;
color: #eeeeee
}
.in1::placeholder {
color: #000e;
}
<!DOCTYPE html>
<html>
<head>
<title>Stopwatch</title>
</head>
<body id="node1">
<input type="number" class="in1" id="time" placeholder="0" value="0">
<br/><br/>
<button class="button1" onclick="button1Action()">Set</button>
</body>
</html>

Javascript StopWatch Wrong Reset Value

I'm trying to create a simple vanilla JS stopwatch. Managed to make it work however when I click my reset button, the value returns my innerHTML change, however it flashes for a quick second before returning a value of 00:00:1 and not 00:00:00. I would have to click it two times before it resets correctly. However, when I pause my timer then reset, it works perfectly. Where is the flaw in my code?
Code:
var status = 0;
var time = 0;
document.getElementById('start').addEventListener('click', start);
document.getElementById('pause').addEventListener('click', pause);
document.getElementById('reset').addEventListener('click', reset);
function start() {
status = 1;
document.getElementById('start').disabled = true;
timer();
}
function pause() {
status = 0;
document.getElementById('start').disabled = false;
}
function reset() {
time = 0;
status = 0;
document.getElementById('label').innerHTML = '00:00:00';
document.getElementById('start').disabled = false;
}
function timer() {
if (status == 1) {
setTimeout(function() {
time++;
var min = Math.floor(time / 10 / 60);
var sec = Math.floor(time / 10 % 60);
var mill = time % 10;
if (min < 10) {
min = '0' + min;
}
if (sec >= 60) {
sec = sec % 60;
}
if (sec < 10) {
sec = '0' + sec;
}
document.getElementById('label').innerHTML = min + ':' + sec + ':' + mill;
timer();
}, 100);
}
}
<div id="wrapper">
<h1 id="label">00:00:00</h1>
<button id="start">Start</button>
<button id="pause">Pause</button>
<button id="reset">Reset</button>
</div>
It's because of the setTimeout, since it's scheduled to run each 100ms, it will run once after you click reset (after a 100ms). In order to prevent it from running after reset, you can store the timeout in a variable and stop it using clearTimeout:
var status = 0;
var time = 0;
var t; // the timeout
document.getElementById('start').addEventListener('click', start);
document.getElementById('pause').addEventListener('click', pause);
document.getElementById('reset').addEventListener('click', reset);
function start() {
status = 1;
document.getElementById('start').disabled = true;
timer();
}
function pause() {
status = 0;
document.getElementById('start').disabled = false;
}
function reset() {
time = 0;
status = 0;
clearTimeout(t); // stop the timeout
document.getElementById('label').innerHTML = '00:00:00';
document.getElementById('start').disabled = false;
}
function timer() {
if (status == 1) {
t = setTimeout(function() { // start the timeout
time++;
var min = Math.floor(time / 10 / 60);
var sec = Math.floor(time / 10 % 60);
var mill = time % 10;
if (min < 10) {
min = '0' + min;
}
if (sec >= 60) {
sec = sec % 60;
}
if (sec < 10) {
sec = '0' + sec;
}
document.getElementById('label').innerHTML = min + ':' + sec + ':' + mill;
timer();
}, 100);
}
}
<div id="wrapper">
<h1 id="label">00:00:00</h1>
<button id="start">Start</button>
<button id="pause">Pause</button>
<button id="reset">Reset</button>
</div>
The reason is that I believe there is a slight latency and you aren't actually clearing the timeout that gets run when you start. It's good practice to keep track of the timeout ID and then clear it appropriately when you need to.
var status = 0;
var time = 0;
var timeoutId;
document.getElementById('start').addEventListener('click', start);
document.getElementById('pause').addEventListener('click', pause);
document.getElementById('reset').addEventListener('click', reset);
function start() {
status = 1;
document.getElementById('start').disabled = true;
timer();
}
function pause() {
status = 0;
document.getElementById('start').disabled = false;
}
function reset() {
time = 0;
status = 0;
clearTimeout(timeoutId);
document.getElementById('label').innerHTML = '00:00:00';
document.getElementById('start').disabled = false;
}
function timer() {
if (status == 1) {
timeoutId = setTimeout(function() {
time++;
var min = Math.floor(time / 10 / 60);
var sec = Math.floor(time / 10 % 60);
var mill = time % 10;
if (min < 10) {
min = '0' + min;
}
if (sec >= 60) {
sec = sec % 60;
}
if (sec < 10) {
sec = '0' + sec;
}
document.getElementById('label').innerHTML = min + ':' + sec + ':' + mill;
timer();
}, 100);
}
}
<div id="wrapper">
<h1 id="label">00:00:00</h1>
<button id="start">Start</button>
<button id="pause">Pause</button>
<button id="reset">Reset</button>
</div>
Its realy simple you have to remove the setTimeout callback function
var timerObj = null; // NEW LINE
var status = 0;
var time = 0;
document.getElementById('start').addEventListener('click', start);
document.getElementById('pause').addEventListener('click', pause);
document.getElementById('reset').addEventListener('click', reset);
function start() {
status = 1;
document.getElementById('start').disabled = true;
timer();
}
function pause() {
status = 0;
document.getElementById('start').disabled = false;
}
function reset() {
clearTimeout(timerObj ); // new LINE
status = 0;
document.getElementById('start').disabled = false;
time = 0;
document.getElementById('label').innerHTML = '00:00:00';
}
function timer() {
if (status == 1) {
timerObj = setTimeout(function() { // changed LINE
time++;
var min = Math.floor(time / 10 / 60);
var sec = Math.floor(time / 10 % 60);
var mill = time % 10;
if (min < 10) {
min = '0' + min;
}
if (sec >= 60) {
sec = sec % 60;
}
if (sec < 10) {
sec = '0' + sec;
}
document.getElementById('label').innerHTML = min + ':' + sec + ':' + mill;
timer();
}, 100);
}
}
<div id="wrapper">
<h1 id="label">00:00:00</h1>
<button id="start">Start</button>
<button id="pause">Pause</button>
<button id="reset">Reset</button>
</div>

Control ball speed in pong

I have this code below, and I'm having a hard time solving this one.
On dotime function, i have the ball speed:
/* HERE */
function dotime() {
move1();
if (myform != null) {
myform.text3.value = display1();
myform.score.value = "" + score;
}
/* ---Ball Speed--- */
if (!oops_flag) timerID = setTimeout("dotime()", 190);
/* ---trying to make ball speed faster--- */
if (score == 1) {
timerID = setTimeout("dotime()", 100 - 30);
}
timerRunning = true;
}
I tried to make the ball move faster but when i do the second "if", the ball just flying too fast.
Thanks in advance,
fufle.
full code:
var crlf = "\r\n";
var x = 0;
var y = 0;
var dx = 1;
var dy = 1;
var s = "";
var u = 0;
var oops_flag = false;
var score = 0;
function move1() {
x += dx;
if (x > 61) {
x -= 2 * Math.abs(dx);
if (dx > 0) dx = -dx;
}
if (x < 0) {
x += 2 * Math.abs(dx);
if (dx < 0) dx = -dx;
}
y += dy;
if (y > 24) {
y -= 2 * Math.abs(dy);
if (dy > 0) dy = -dy;
if (Math.abs(x - 2 * u - 1) > 2) {
oops_flag = true;
} else {
score += 1;
}
}
if (y < 0) {
y += 2 * Math.abs(dy);
if (dy < 0) dy = -dy;
}
}
function display1() {
var s1 = ""
var i, j;
if (oops_flag) return " Unlucky, Play again?"
for (j = 0; j < 25; j++) {
for (i = 0; i < 62; i++) {
/* BALL */
if (j == y && i == x) s1 += "🔴";
else s1 += " ";
}
s1 += crlf;
}
/* DEFENDER */
var s2 = "";
for (i = 0; i < 31; i++) {
if (u == i) s2 += "â–„â–„â–„â–„â–„";
else s2 += " ";
}
return (s1 + s2);
}
var timerID = null;
var timerRunning = false;
var myform;
function stopclock() {
if (timerRunning) clearTimeout(timerID);
timerRunning = false;
}
function startclock(form) {
myform = form;
oops_flag = false;
score = 0;
if (navigator.userAgent.indexOf("Mac") > 2) crlf = "\n";
stopclock();
dotime();
// var id= setInterval(frameElement,10000);
}
/* HERE */
function dotime() {
move1();
if (myform != null) {
myform.text3.value = display1();
myform.score.value = "" + score;
}
if (!oops_flag) timerID = setTimeout("dotime()", 100);
if (score == 1) {
timerID = setTimeout("dotime()", 100 - 30);
}
timerRunning = true;
}
Looks like you have two timers running so you need to make it so only one will run.
if (!oops_flag) {
var speed = 100;
if (score===1) speed = 70;
timerID = setTimeout(dotime, speed);
}
or with a ternary operator
if (!oops_flag) {
var speed = (score===1) ? 70 : 100;
timerID = setTimeout(dotime, speed);
}

Categories

Resources