JavaScript Dynamically added / removed div - javascript

I want to create multiple divs dynamically. Each one should remove itself after set amount of time. I have functions to create divs and to coutdown time. I don't know how to connect it together. And one more question, how to manage ids of dynamically added elements?
function creatediv(e)
{
ward = document.createElement('div');
ward.className="dynamic";
ward.id = id;
id++;
ward.style.pixelLeft = mouseX(e);
ward.style.pixelTop = mouseY(e);
document.body.appendChild(ward);
}
function timer(ID, time)
{
if(time > 0)
{
--time;
s=time%60;
m=Math.floor((time%3600)/60);
var S = document.getElementById(ID);
S.style.color = "white";
document.getElementById(ID).innerHTML =((m<10)?"0"+m:m)+":"+((s<10)?"0"+s:s);
setTimeout(function () {timer(ID,time)}, 1000);
}
if(time == 0)
{
return true;
}
}
Any hint is very much appreciated.
Thanks

function creatediv(e) {
ward = document.createElement('div');
ward.className = "dynamic";
ward.id = id;
id++;
ward.style.pixelLeft = mouseX(e);
ward.style.pixelTop = mouseY(e);
document.body.appendChild(ward);
timer(ward.id, THE_TIME_YOU_WANT);
}
function timer(ID, time) {
if (time > 0) {
--time;
s = time % 60;
m = Math.floor((time % 3600) / 60);
var S = document.getElementById(ID);
S.style.color = "white";
S.innerHTML = ((m < 10) ? "0" + m : m) + ":" + ((s < 10) ? "0" + s : s);
setTimeout(function () {
timer(ID, time)
}, 1000);
}
else {
// remove the div.
}
}

Related

Javascript setInterval flickering

I'm trying to create a chess clock using JavaScript. I've settle almost all of the issues with the clock's functionality except for this one. I'm using setInterval to essentially create the "countdown" effect on each player's clock. However, when it is triggered with the method I'm currently using the clock flickers. From my understanding/research, this is likely because there are overlapping 'intervals' that cause the code to try to display multiple intervals at the same time. Essentially the clock buttons (stopclock and stopclock2) when clicked call the functions on the bottom of my code. Could anyone provide some input on my code (below) and why this might be occurring?
clear1mils = "";
clear2mils = "";
//Clock Functions
function countdownmils2() {
document.getElementById("milsvalue2").innerHTML = --mil2;
if (mil2 == 0) {
mil2 = mil2 + 59;
if (sec2 == 0) {
if (min2 == 0) {
clearInterval(clear2mils);
document.getElementById("milsvalue2").innerHTML = "00";
}else if (min2 !== 0) {
sec2 = 60;
document.getElementById("minutesvalue2").innerHTML = --min2;
document.getElementById("secondsvalue2").innerHTML = --sec2;
}
}else if (sec2 !== 0) {
document.getElementById("secondsvalue2").innerHTML = --sec2;
if (sec2 <= 10) {
document.getElementById("secondsvalue2").innerHTML = "0" + sec2;
}
}
}else if (mil2 <= 10) {
document.getElementById("milsvalue2").innerHTML = "0" + mil2;
}
}
function countdownmils() {
document.getElementById("milsvalue").innerHTML = --mil;
if (mil == 0) {
mil = mil + 59;
if (sec == 0) {
if (min == 0) {
clearInterval(clear1mils);
document.getElementById("milsvalue").innerHTML = "00";
}else if (min !== 0) {
sec = 60;
document.getElementById("minutesvalue").innerHTML = --min;
document.getElementById("secondsvalue").innerHTML = --sec;
}
}else if (sec !== 0) {
document.getElementById("secondsvalue").innerHTML = --sec;
if (sec <= 10) {
document.getElementById("secondsvalue").innerHTML = "0" + sec;
}
}
}else if (mil <= 10) {
document.getElementById("milsvalue").innerHTML = "0" + mil;
}
}
//Clock 1
document.querySelector("#stopclock").addEventListener("click", () => {
clear2mils = setInterval(countdownmils2, 10);
clearInterval(clear1mils);
document.getElementById("stopclock").innerHTML = "DOWN";
document.getElementById("stopclock2").innerHTML = "UP";
document.getElementById("stopclock").setAttribute("disabled", "true");
document.getElementById("stopclock2").removeAttribute("disabled", "true");
});
//Clock 2
document.querySelector("#stopclock2").addEventListener("click", () => {
clear1mils = setInterval(countdownmils, 10);
clearInterval(clear2mils);
document.getElementById("stopclock2").innerHTML = "DOWN";
document.getElementById("stopclock").innerHTML = "UP";
document.getElementById("stopclock2").setAttribute("disabled", "true");
document.getElementById("stopclock").removeAttribute("disabled", "true");
});

Having issue resetting JS stopwatch

I made a little typing game that reveals some random text and you have to type the same in, so that you can test your typing speed. the users has the ability to play again and again, the issue is that when the user types play again, the stopwatch does not begin as it did the first time.
Can anyone help me with making the stopwatch restart everytime the user clicks on the play again button?
[ full code is here] (https://jsfiddle.net/kisho/ncbxd9o4/#&togetherjs=qD5bT8vLiw)
js portion-
const textDisplay = document.querySelector('#text-display');
const input = document.querySelector('#input');
const btn = document.querySelector('#btn');
const textBox = document.querySelector('#text-box');
const countdown = document.querySelector('#countdown');
const stopwatch = document.querySelector('#stopwatch');
const successMessege = document.querySelector('#success-messege');
const stopwatchTime = document.querySelector('#stopwatch-time');
btn.addEventListener('click', runGame);
function runGame() {
if ((btn.innerText = 'Play again')) {
playAgain();
fetchQuote();
countownTimer();
confirmQuote();
} else {
fetchQuote();
countownTimer();
confirmQuote();
}
}
function fetchQuote() {
fetch('https://api.quotable.io/random')
.then((res) => {
return res.json();
})
.then((data) => {
textDisplay.innerText = data.content;
});
}
function countownTimer() {
if (timer !== undefined) {
clearInterval(timer);
}
var timeleft = 2;
var downloadTimer = setInterval(function() {
if (timeleft <= 0) {
clearInterval(downloadTimer);
document.getElementById('countdown').innerHTML = 'Start Typing!';
input.classList.remove('displayNone');
runningStopwatch.classList.remove('displayNone');
begin();
} else {
document.getElementById('countdown').innerHTML = timeleft + ' seconds remaining';
}
timeleft -= 1;
}, 1000);
}
function confirmQuote() {
if ((countdown.innerHTML = 'Start typing!')) {
input.addEventListener('keyup', function(event) {
if (event.keyCode === 13) {
if (textDisplay.innerText === input.value) {
btn.innerText = 'Play again';
// textBox.classList.add('displayNone');
hold();
} else successMessege.innerText = 'Missed something there, try again!!';
}
});
}
}
function playAgain() {
textBox.classList.remove('displayNone');
input.classList.add('displayNone');
input;
input.value = '';
successMessege.innerText = '';
}
let ms = 0,
s = 0,
m = 0;
let timer;
let runningStopwatch = document.querySelector('.running-stopwatch');
function begin() {
timer = setInterval(run, 10);
}
function run() {
runningStopwatch.textContent =
(m < 10 ? '0' + m : m) + ': ' + (s < 10 ? '0' + s : s) + ': ' + (ms < 10 ? '0' + ms : ms);
ms++;
if (ms == 100) {
ms = 0;
s++;
}
if (s == 60) {
s = 0;
m++;
}
}
function hold() {
clearInterval(timer);
successMessege.innerText = `Nice job! You just typed in x seconds!`;
}
function stop() {
(ms = 0), (s = 0), (m = 0);
runningStopwatch.textContent =
(m < 10 ? '0' + m : m) + ': ' + (s < 10 ? '0' + s : s) + ': ' + (ms < 10 ? '0' + ms : ms);
}
You are not handling the clearInterval correctly.
You are clearing the interval only if one ends the game successfully.
My solution would be:
When calling the countownTimer() function, the first thing you should do, is to check if the interval timer is still running.
function countownTimer() {
if (timer !== undefined) {
clearInterval(timer);
}
// [...]
}
The next thing would be, to start the interval every time begin() gets called.
function begin() {
timer = setInterval(run, 10);
}

Why clearInterval is not stopping setInterval?

I'm trying to make a Timer for a project that record audios and while on the making, I've faced with this problem: setInterval is not stopping, why?
I have the following code:
/** Audio **/
var timerseconds = 0;
$('.audio-recorder-dialog-con').on('click', '#record', function() {
gotrecordval = document.getElementById("record").value;
//Crónometro
var timerseconds = setInterval(function() {
rseconds = parseInt(document.getElementById("r-seconds").value);
if (rseconds == 59) {
document.getElementById("r-seconds").value = "00";
}
rseconds = parseInt(document.getElementById("r-seconds").value);
rseconds += 1;
if (rseconds < 10) {
document.getElementById("r-seconds").value = ("00" + rseconds).substr(-2);
}
if (rseconds >= 10) {
document.getElementById("r-seconds").value = rseconds;
}
}, 1000);
//
if (gotrecordval == "Empezar a Grabar Audio") {
document.getElementById("record").value = "Detener/Subir";
}
if (gotrecordval == "Detener/Subir") {
document.getElementById("record").value = "Empezar a Grabar Audio";
$('.audio-recorder-dialog-con').fadeOut(500);
$(".contenido-dialog-new-d").fadeIn(500);
$("#aviaudio").fadeIn(500);
clearInterval(timerseconds);
}
});
--FIXED--
I've fixed it by adding this inside the setInterval:
//Crónometro
var timerseconds = setInterval(function(){
rseconds = parseInt(document.getElementById("r-seconds").value);
if(rseconds==59){document.getElementById("r-seconds").value = "00";}
rseconds = parseInt(document.getElementById("r-seconds").value);
rseconds+=1;
if(rseconds<10){document.getElementById("r-seconds").value = ("00" + rseconds).substr(-2);}
if(rseconds>=10){document.getElementById("r-seconds").value = rseconds;}
--Code added-
$('html, body').on('click', '.open-audio', function(){
clearInterval(timerseconds);
});
--
}, 1000);
//
".open-audio" is an image that opens the recording dialog for the user, so when you re-open it, the clearInterval works.
The solution you added to your question is not sound: this will create a new event handler at every 'tick' of the setInterval timer. That is not the right way to do it.
Instead, only execute setInterval in the case you need to start it, so put it inside the first if:
if (gotrecordval == "Empezar a Grabar Audio") {
//Crónometro
var timerseconds = setInterval(function() {
rseconds = parseInt(document.getElementById("r-seconds").value);
if (rseconds == 59) {
document.getElementById("r-seconds").value = "00";
}
rseconds = parseInt(document.getElementById("r-seconds").value);
rseconds += 1;
if (rseconds < 10) {
document.getElementById("r-seconds").value = ("00" + rseconds).substr(-2);
}
if (rseconds >= 10) {
document.getElementById("r-seconds").value = rseconds;
}
}, 1000);
//
document.getElementById("record").value = "Detener/Subir";
}

JavaScript timer in my program stops in unpredictable way

I'm a completely beginner and I write code in my free time. Can anyone explain me please why sometimes my Pomodore Clock is stuck when it hits 0 0 1. (hours, minutes, seconds)
I can start it in one tab in chrome and it will work for unpredictable amount of cycles and then for no reason it will stop at 0 0 1, just before starting next cycle. I want it to work continuous (work, break, work, break, etc.) until I hit reset button...
Is there better way to handle time in JS?
Code:
// Code wrapped in a closure to avoid global variables
(function () {
let countdown;
let timeIsRunnig = false;
let actionTypeSwitch = "Work";
const timerDisplay = document.querySelector(".display__time-left");
const infoDisplay = document.querySelector(".display__info");
const endTime = document.querySelector(".display__end-time");
const buttons = document.querySelectorAll("[data-time]");
const breakSettings = document.querySelectorAll(".settings__breakButton");
const workSettings = document.querySelectorAll(".settings__workButton");
const breakValue = document.querySelector("#valueBreak");
const workValue = document.querySelector("#valueWork");
const buttonMain = document.querySelector("#buttonMain");
let workValueSettings = 25; // Default work session value in min
let breakValueSettings = 5; // Default break session value in min
workValue.textContent = workValueSettings + ' min';
breakValue.textContent = breakValueSettings + ' min';
timerDisplay.textContent = `${ workValueSettings}:00`;
infoDisplay.textContent = "Are you ready?";
endTime.textContent = "Press START";
function timer(seconds) {
// Clear any existing timers
clearInterval(countdown);
// Current time in ms
const now = Date.now();
const future = now + seconds * 1000;
displayTimeLeft(seconds);
displayEndTime(future);
function timeCalc() {
const secondsLeft = Math.round((future - Date.now()) / 1000);
// Check if we should stop it
if (secondsLeft < 0) {
clearInterval(countdown);
return;
}
// Display it
displayTimeLeft(secondsLeft);
}
countdown = setInterval(timeCalc, 1000);
}
function startTimer() {
const seconds = workValueSettings * 60;
actionTypeSwitch = "Work";
infoDisplay.textContent = "Working hard!";
timer(seconds);
}
function startBreak() {
const seconds = breakValueSettings * 60;
actionTypeSwitch = "Break";
infoDisplay.textContent = "Short break!";
timer(seconds);
}
function resetTimer() {
const seconds = workValueSettings * 60;
// Clear any existing timers
clearInterval(countdown);
// Refresh display
displayTimeLeft(seconds);
infoDisplay.textContent = "Are you ready?";
endTime.textContent = "Press START";
}
function startAndReset() {
let name = "START";
if (timeIsRunnig === false) {
timeIsRunnig = true;
name = "RESET";
this.innerHTML = name;
startTimer();
} else {
timeIsRunnig = false;
name = "START";
this.innerHTML = name;
resetTimer();
}
}
function playSoundStartBreak() {
// Returns the first Element within the document
// that matches the specified group of selectors.
const audio = document.querySelector(`audio[data-sound="workDone"]`);
if(!audio) return; // Stop the function from running
audio.currentTime = 0; // Rewind to the start
audio.play();
}
function playSoundBackToWork() {
// Returns the first Element within the document
// that matches the specified group of selectors.
const audio = document.querySelector(`audio[data-sound="backToWork"]`);
if(!audio) return; // Stop the function from running
audio.currentTime = 0; // Rewind to the start
audio.play();
}
function displayTimeLeft(sec) {
const hours = parseFloat(Math.floor(sec / 3600));
const minutes = parseFloat(Math.floor(sec / 60));
const remainderMinutes = parseFloat(minutes % 60);
const remainderSeconds = parseFloat(sec % 60);
console.log(hours, remainderMinutes, remainderSeconds);
// Play sound when timer gets to 0
if (parseFloat(sec) === 0) {
if (actionTypeSwitch === "Work") {
playSoundStartBreak()
startBreak();
} else {
playSoundBackToWork();
startTimer();
}
}
// Hide hours when hours is 0
let hoursFirstStatement = hours < 10 ? "0" : "";
let hoursSecondStatement = hours;
let colon = ":";
if (hours === 0) {
hoursFirstStatement = "";
hoursSecondStatement = "";
colon = "";
}
// This `${}` allows adding javascript variables in strings
const display = `${hoursFirstStatement}${hoursSecondStatement}${colon}${
remainderMinutes < 10 ? "0" : ""}${remainderMinutes}:${
remainderSeconds < 10 ? "0" : ""}${remainderSeconds}`;
timerDisplay.textContent = display;
document.title = display + " " + "(" + actionTypeSwitch + ")";
}
function displayEndTime(timestamp) {
const end = new Date(timestamp);
const hours = end.getHours();
const minutes = end.getMinutes();
endTime.textContent = `This session ends at ${hours < 10 ? "0" : ""}${hours}:${
minutes < 10 ? "0" : ""}${minutes}`;
}
function changeBreakSettings() {
const breakChangeValue = parseInt(this.dataset.settings);
if ((breakValueSettings <= 1 && breakChangeValue === -1) ||
(breakValueSettings >= 30 && breakChangeValue === 1)) {
return; // Do nothing when this conditions are fulfilled
} else {
breakValueSettings = breakValueSettings + breakChangeValue;
breakValue.textContent = breakValueSettings + ' min';
}
}
function changeWorkSettings() {
const workChangeValue = parseInt(this.dataset.settings);
if ((workValueSettings <= 5 && workChangeValue === -1) ||
(workValueSettings >= 120 && workChangeValue === 1)) {
return; // Do nothing when this conditions are fulfilled
} else {
workValueSettings = workValueSettings + workChangeValue;
workValue.textContent = workValueSettings + ' min';
}
}
breakSettings.forEach(button => button.addEventListener("click", changeBreakSettings));
workSettings.forEach(button => button.addEventListener("click", changeWorkSettings));
buttonMain.addEventListener("click", startAndReset);
}());
You need to do clearInterval() against timeCalc & update the display on the case of secondsLeft < 0. Because when you do not clear it, when it is showing "1 second left", the call of timeCalc will goes into the if statement and return, and never update the display and timeCalc is never clear and you get into infinite loop.

Uneven Countup Timer Jquery Based on Time of Day

I was looking for a jquery countup timer that was based on the time of day, and I was struggling to find one so here I just wrote my own. Here it is for anyone who's looking for one.
The objective is to take the time of day, calculate a percentage through the day of that current time, multiply it by an objective sum and start adding to create a realistic timing scenario. My timers are firing to create the simulation of an unsteady data flow, but you can change it to a steady increase easily.
The element with the number is #counter, and the objective total is the 3.5mm.
var currentNumber;
$(document).ready(function (e) {
var currDate = new Date();
var mins = currDate.getMinutes();
var hours = currDate.getHours();
var seconds = currDate.getSeconds();
var combined = (hours * 60 * 60) + (mins * 60) + seconds;
var percentage = (combined / 90000);
var startingPoint = Math.round(3500000 * percentage);
currentNumber = startingPoint;
$('#counter').html(formatNumber(startingPoint));
setTimeout(function () {
updateNumber(currentNumber)
}, 100);
});
function updateNumber(startingPoint) {
if (startingPoint % 58 === 0) {
startingPoint += 5;
currentNumber = startingPoint;
$('#counter').html(formatNumber(currentNumber));
setTimeout(function () {
updateNumber(currentNumber)
}, 850);
} else if (startingPoint % 22 === 0) {
startingPoint += 4;
currentNumber = startingPoint;
$('#counter').html(formatNumber(currentNumber));
setTimeout(function () {
updateNumber(currentNumber)
}, 500);
} else if (startingPoint % 6 === 0) {
startingPoint += 1;
currentNumber = startingPoint;
$('#counter').html(formatNumber(currentNumber));
setTimeout(function () {
updateNumber(currentNumber)
}, 75);
} else {
startingPoint += 5;
currentNumber = startingPoint;
$('#counter').html(formatNumber(currentNumber));
setTimeout(function () {
updateNumber(currentNumber)
}, 250);
}
}
function formatNumber(number) {
return addCommas((number).toFixed(0));
}
function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}

Categories