Countdown with setInterval going too fast - javascript

could someone help me, I would like to know how to make it so the countdown doesn't go faster every time I click? I assume clear interval but not sure what I need to put. Thanks
var cD = 100;
function countDown() {
if (cD > 0) {
cD -= 1;
$(".countdown").html(cD +"s");
}
}
$(".countdown-trigger").click(function(){
cD = 100;
setInterval(countDown, 10);
});
.countdown-trigger {
height: 50px;
width: 100px;
background-color: blue;
}
.countdown {
font-family: "Teko", sans-serif;
font-size: 100px;
line-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown">
</div>
<div class="countdown-trigger">
</div>

The issue is because you never clear the previous timeout on each successive click, hence after 3 clicks you have three timers all decrementing the value every 10ms.
To fix this call clearTimeout() when cD hits 0. Also note that you would need a mechanism to prevent starting multiple intervals while the previous one is still running, or else you'll have the same issue. To do that you can use a boolean flag. Try this:
var cD = 100, interval, running = false;
function countDown() {
if (cD > 0) {
cD -= 1;
$(".countdown").html(('00' + cD).slice(-2) + "s");
} else {
clearInterval(interval);
running = false;
}
}
$(".countdown-trigger").click(function() {
if (running)
return;
cD = 100;
running = true;
interval = setInterval(countDown, 10);
});
.countdown-trigger {
height: 50px;
width: 100px;
background-color: blue;
}
.countdown {
font-family: "Teko", sans-serif;
font-size: 100px;
line-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown"></div>
<div class="countdown-trigger"></div>

var cD = 100;
var myOtherVar;
function countDown() {
if (cD > 0) {
cD -= 1;
$(".countdown").html(cD +"s");
} else {
clearInterval(myOtherVar);
}
}
$(".countdown-trigger").click(function(){
cD = 100;
myOtherVar = setInterval(countDown, 10);
});
.countdown-trigger {
height: 50px;
width: 100px;
background-color: blue;
}
.countdown {
font-family: "Teko", sans-serif;
font-size: 100px;
line-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown">
</div>
<div class="countdown-trigger">
</div>
You're right. You just need to clear your interval. Every time you click the area it sets up another set of events that occur every 10ms & that is why it continues to get faster & faster.

Related

How to delay JS function from running until 5 seconds after page loads

I want this to run but so that it doesn't for 5 seconds after the page fully loads. How would I go about achieving this, I believe its a ,500 somewhere but I am not sure where this would go.
If you have any questions please ask!
Thank you in advance for you help on this matter, its very much appreciated!
$(".demoBookedContentClose").click(function(){
$("body").addClass("demoBookedHidden");
});
function shuffle(array) {
var currentIndex = array.length,
temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
var queue = [];
function setUp() {
var elems = $(".demoBooked").get();
queue = shuffle(elems);
showNext();
}
function showNext() {
var elem = queue.pop();
if (elem) {
$(elem)
.fadeIn(2000)
.delay(5000)
.fadeOut(1000, function(){ setTimeout(showNext,25000); });
} else {
setUp();
}
}
setUp();
.demoBooked {
background: #fff;
box-shadow: 0 1px 2px rgba(0,0,0,0.05), 0 2px 4px rgba(0,0,0,0.08);
border: 1px solid #dddddd;
padding: 20px;
border-radius: 8px;
display: none;
}
.demo-booked-section {
position: fixed;
bottom: 10px;
left: 10px;
z-index: 2;
}
.demoBooked h3 {
font-size: 22px;
font-weight: 900;
margin-bottom: 4px;
}
.demoBooked img {
max-width: 50px;
margin-top: -55px;
border-radius: 100%;
display: inline-block;
}
.demoBookedContent {
display: inline-block;
padding-left: 20px;
}
.demoBooked p {
font-size: 18px;
line-height: 20px;
}
.demoBookedTime {
color: #e12826;
}
.demoBookedContentClose {
position: absolute;
right: 15px;
top: 10px;
font-size: 10px;
cursor: pointer;
}
.demoBookedHidden .demo-booked-section {
display: none!important;
}
.demoBookedTime {
font-size: 15px;
}
#media only screen and (max-width: 768px) {
.demo-booked-section {
display: none!important;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="demo-booked-section">
<div class="demoBooked">
<img src="/wp-content/uploads/2021/01/william-diaz.jpg">
<div class="demoBookedContent">
<span class="demoBookedContentClose">X</span>
<h3>William Diaz</h3>
<p class="demoBookedText">Just started a FREE trial</p>
<p class="demoBookedTime">1hrs ago</p>
</div>
</div>
<div class="demoBooked">
<img src="/wp-content/uploads/2021/01/freya-smith.jpg">
<div class="demoBookedContent">
<span class="demoBookedContentClose">X</span>
<h3>Freya Smith</h3>
<p class="demoBookedText">Just started a FREE trial</p>
<p class="demoBookedTime">3hrs ago</p>
</div>
</div>
</div>
You can delay your function 5 seconds (5000 ms) with an 'setTimeout' functions after your web load:
<script>
window.onload = function() {
setTimeout(function(){
//Your function here
},5000);
}
</script>
Since you want the function to be fired up 5 seconds after the page is fully loaded you will be using a combination of two functions.
I see you are using jQuery in your website
The below code waits until the page is fully loaded then fires up the code inside the brackets.
$( document ).ready(function() {
// code here
});
So inside the above code you will add your 5 seconds waiting function
setTimeout(function(){
// Magic happens here
},5000);
The final code is
$( document ).ready(function() {
setTimeout(function(){
// Magic happens here
},5000);
});
You can use setTimeout which will wait the specified number of milliseconds before running whatever is between the curly braces (in this case I put your setUp function there because I assume that's what you meant by your question).
Because you want the function to run 5 seconds after the page is fully loaded you need to surround the code in a call to window.onload which will make sure that setTimeout only runs once the page has been fully loaded.
window.onload = function() {
setTimeout(function() { setUp(); }, 5000);
}

How to make a count down reset

I'm trying to make a count down so that every 20 sec an alert pops up. I want it to go from 20 to 0 to 20 over and over. I have it working, but it only works once. The rage function dosen't need to be changed, it's the msg function i'm having trouble with. Here's my code.
function rage() {
var i = document.getElementsByName("msg")[6];
var message = document.getElementById("message");
const affichemsg = document.querySelector("msg");
for (i = 0; i < 1; i++) {
message.innerHTML += "Es-tu près ";
}
}
setInterval(rage, 350);
var decompteur = setInterval(msg, 1000);
var temps;
function msg() {
var idTemps = document.getElementById("temps");
temps = parseInt(idTemps.innerHTML);
temps = temps - 1;
idTemps.innerHTML = temps;
if (--temps <= 0) {
alert("!!!!!ES-TU PRÈS!!!!!");
clearInterval(temps);
msg();
idTemps = 20;
var decompteur = setInterval(msg, 1000);
}
}
.titre2 {
width: 650px;
margin: auto;
text-align: center;
border-radius: 35px;
color: #000000;
background-color: #ff0000;
padding: 5px;
margin-bottom: 30px;
}
.bouton {
transition-duration: 0.4s;
border-width: 1px;
cursor: pointer;
}
.boutonOui {
background-color: rgb(234, 234, 234);
}
.boutonOui:hover {
background-color: rgb(177, 177, 177);
}
<div class="header">
<h1 class="titre2">Es-tu près</h1>
</div>
<button
class="bouton boutonOui"
id="boutonOui"
onclick="window.location.href='jeu_educatifs2.html'"
>
Oui
</button>
<div id="temps">20</div>
<div id="message"></div>
<div id="msg" value="6"></div>
the first problem here is that you don't use correctly the method clearInterval. It takes as argument the id of the "timer" created with setInterval. setInterval return directly the id so actually stored it in your variable decompteur and you should use something like that to clear the timer : clearInterval(decompteur).
Also be sure to reset the idTemps with idTemps.innerHTML = 20. Then I don't really understand... Why would you clear the interval then rebuild the same again when you can just set the idTemps.innerHTML so your interval will use the 20 for temps at the next iteration ?
PS: ça fait plaisir de voir un peu de français sur stack :)
You should rewrite your code this way :
function rage() {
var i = document.getElementsByName("msg")[6];
var message = document.getElementById("message");
const affichemsg = document.querySelector("msg");
for (i = 0; i < 1; i++) {
message.innerHTML += "Es-tu près ";
}
}
setInterval(rage, 350);
var decompteur = setInterval(msg, 1000);
function msg() {
var idTemps = document.getElementById("temps");
var temps = parseInt(idTemps.innerHTML) - 1;
idTemps.innerHTML = temps;
if (--temps == 0) {
alert("!!!!!ES-TU PRÈS!!!!!");
idTemps.innerHTML = "20";
}
}
// when you need to, stop decompteur with :
// clearInterval(decompteur);
.titre2 {
width: 650px;
margin: auto;
text-align: center;
border-radius: 35px;
color: #000000;
background-color: #ff0000;
padding: 5px;
margin-bottom: 30px;
}
.bouton {
transition-duration: 0.4s;
border-width: 1px;
cursor: pointer;
}
.boutonOui {
background-color: rgb(234, 234, 234);
}
.boutonOui:hover {
background-color: rgb(177, 177, 177);
}
<div class="header">
<h1 class="titre2">Es-tu près</h1>
</div>
<button class="bouton boutonOui" id="boutonOui" onclick="window.location.href='jeu_educatifs2.html'">
Oui
</button>
<div id="temps">20</div>
<div id="message"></div>
<div id="msg" value="6"></div>
This keep as much of your code as possible, but as Rojo said, your code is very inefficent and there are a lot of things to improve.
Currently, your code is very inefficient. Rather than having your variable temps read from the DOM, you should have the variable update itself:
var temps = 20;
function msg() {
--temps;
}
setInterval(msg, 1000);
Second, you shouldn't be including var inside of that if statement:
if (countdown === 0) {
alert("!!!!!ES-TU PRÈS!!!!!");
clearInterval(decompteur);
// msg(); // You don't need this
temps = 20;
decompteur = setInterval(msg, 1000); // I removed the var
}
Also, you had your variables mixed up (which I fixed)
function rage() {
var i = document.getElementsByName("msg")[6];
var message = document.getElementById("message");
const affichemsg = document.querySelector("msg");
for (i = 0; i < 1; i++) {
message.innerHTML += "Es-tu près ";
}
}
setInterval(rage, 350);
var decompteur = setInterval(msg, 1000);
var temps = 20;
var idTemps = document.getElementById("temps"); // I also moved this outside
function msg() {
--temps;
idTemps.innerHTML = temps;
if (temps === 0) {
alert("!!!!!ES-TU PRÈS!!!!!");
clearInterval(decompteur);
//msg(); //You don't need this
temps = 20;
decompteur = setInterval(msg, 1000);
}
}
.titre2 {
width: 650px;
margin: auto;
text-align: center;
border-radius: 35px;
color: #000000;
background-color: #ff0000;
padding: 5px;
margin-bottom: 30px;
}
.bouton {
transition-duration: 0.4s;
border-width: 1px;
cursor: pointer;
}
.boutonOui {
background-color: rgb(234, 234, 234);
}
.boutonOui:hover {
background-color: rgb(177, 177, 177);
}
<div class="header">
<h1 class="titre2">Es-tu près</h1>
</div>
<button
class="bouton boutonOui"
id="boutonOui"
onclick="window.location.href='jeu_educatifs2.html'"
>
Oui
</button>
<div id="temps">20</div>
<div id="message"></div>
<div id="msg" value="6"></div>
The following code prints the counter value each second and every 20 seconds it prints ALERT. Try to use a similar code for your example because your code is not very clear.
let counter = 0;
setInterval(() => {
counter++;
if (counter % 20 == 0) {
console.log("ALERT! ");
}
console.log("Counter Value: " + (counter % 20));
}, 1000);

Update element with ajax don't affect until for loop end

I want to print a lot of numbers ONE-BY-ONE with AJAX.
something like this: (each new line is update of previous line!)
output is:
1
12
123
1234
12345
123456
...
I tried a lot and read a lot of this same problem, but i couldn't find my right Answer.
The real problem is every FOR LOOP in javascript will NO affect the DOM after it will END the loop. I just want update the DOM inside the FOR LOOP while working on a long running job.
Please look at my code.
$("#btn").on("click", dowork);
function dowork() {
document.getElementById("foo").innerHTML = "working";
setTimeout(function() {
var counter = 100; // i want assign counter = 2000000000
for (var i = 0; i < counter; i++) {
document.getElementById("print_here").innerHTML += i;
}
document.getElementById("foo").innerHTML = "done!";
}, 50);
}
#btn {
background: #1f1f1f;
padding: 10px;
font-weight: bolder;
color: #fff;
width: 50%;
margin: auto;
margin-top: 10px;
text-align: center;
cursor: pointer;
}
#print_here {
overflow-wrap: break-word;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn">CLICK TO DO WORK</div>
<div id="foo"></div>
<div id="print_here"></div>
Thanks for any answer and help to solve this problem.
Your DOM is "locked" while it is being updated and redrawn ones the loop is done. You can free up the resource to let the DOM update each time wrapping your DOM change in a setTimeout, similar to:
setTimeout(function(){
document.getElementById("print_here").innerHTML += i;
},1);
To ensure setTimeout uses the correct value for i use let i instead of var i
$("#btn").on("click", dowork);
function dowork() {
document.getElementById("foo").innerHTML = "working";
var counter = 3000; // i want assign counter = 2000000000
for (let i = 0; i < counter; i++) {
setTimeout(function() {
document.getElementById("print_here").innerHTML += i;
}, 1);
}
document.getElementById("foo").innerHTML = "done!";
}
#btn {
background: #1f1f1f;
padding: 10px;
font-weight: bolder;
color: #fff;
width: 50%;
margin: auto;
margin-top: 10px;
text-align: center;
cursor: pointer;
}
#print_here {
overflow-wrap: break-word;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn">CLICK TO DO WORK</div>
<div id="foo"></div>
<div id="print_here"></div>
I want change the #foo into "done!" after the FOR statement is END
You could check if you are at your last item you process within the setTimeout, similar to:
if (i == counter - 1){
document.getElementById("foo").innerHTML = "done!";
}
$("#btn").on("click", dowork);
function dowork() {
document.getElementById("foo").innerHTML = "working";
var counter = 3000; // i want assign counter = 2000000000
for (let i = 0; i < counter; i++) {
setTimeout(function() {
document.getElementById("print_here").innerHTML += i;
if (i == counter - 1){
document.getElementById("foo").innerHTML = "done!";
}
}, 1);
}
}
#btn {
background: #1f1f1f;
padding: 10px;
font-weight: bolder;
color: #fff;
width: 50%;
margin: auto;
margin-top: 10px;
text-align: center;
cursor: pointer;
}
#print_here {
overflow-wrap: break-word;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn">CLICK TO DO WORK</div>
<div id="foo"></div>
<div id="print_here"></div>
You need to let the call stack complete so the browser can do its work on the page. If you bog down the one main thread, page updates aren't going to occur.
One way to do this is use setImmediate or nextTick. This is non-standard, so check this polyfill: https://www.npmjs.com/package/browser-next-tick
Basically, you do an iteration, then tell the browser to do the next iteration as soon as possible... and this occurs on a fresh call stack.
Here is the working code for you:
$("#btn").on("click", dowork);
function dowork() {
document.getElementById("foo").innerHTML = "working";
setTimeout(function() {
var i, j, row = 5;
var html = "";
for (i = 1; i <= row; i++) {
for (j = 1; j <= i; j++) {
html += "<span>" + j + "</span>";
}
html += "</br>";
}
console.log(html);
document.getElementById("print_here").innerHTML = html;
}, 50);
}
#btn {
background: #1f1f1f;
padding: 10px;
font-weight: bolder;
color: #fff;
width: 50%;
margin: auto;
margin-top: 10px;
text-align: center;
cursor: pointer;
}
#print_here {
overflow-wrap: break-word;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn">CLICK TO DO WORK</div>
<div id="foo"></div>
<div id="print_here"></div>
Rows is the number of rows you want to print.

how to get soundcloud follower count using JavaScript

Does anyone know how to put the amount of followers from soundcloud into a JavaScript variable so I can have it ring a notification when I hit 1K follows I have code that I have got from code pen by another user that I have forked
my code is -> here
and if you do not want to go to see it I have included it below
HTML
' <head>
<meta http-equiv="refresh" content="5">
</head>
<div class="card">
<div class="icon">
<i class="fa fa-soundcloud fa-3x"></i>
</div>
<div class="count"></div>
<span>followers</span>
</div>
<audio id="myAudio">
<source src="file:///home/chronos/u-95bb3831b1fe3a2c6fb7e71045f629e9434b1484/Downloads/echoed-ding.mp3" type="audio/mpeg">
</audio>
<p id="demo"></p>
<button onclick="wright()" type="button">wright</button>
<!--
<button onclick="pauseAudio()" type="button">Pause Audio</button>
!-->'
css
#import url(https://fonts.googleapis.com/css?family=Montserrat:400,700|Open+Sans+Condensed:300);
$primary-font: "Montserrat";
$secondary-font: "Open Sans Condensed";
body {
background-color: #1F282D;
.card {
width: 145px;
height: 187px;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
position: absolute;
opacity: 0;
transition: .1s opacity;
/*border: 1px solid #fff;
border-radius: 6px;*/
&.visible {
opacity: 1;
}
.icon {
position: relative;
top: .85em;
}
.count {
font-family: $primary-font;
font-size: 4em;
line-height: 1em;
bottom: 0.9em;
}
span {
font-family: $secondary-font;
text-transform: uppercase;
font-size: 1.1em;
letter-spacing: 2px;
bottom: 1.1em;
}
.count, span, .icon i.fa {
position: absolute;
left: 50%;
transform: translateX(-50%);
color: #fff;
}
}
}
javascript
var abbrev = {
1e3: "K",
1e6: "M"
};
aja()
.method("GET")
.url('https://api.soundcloud.com/users/awesomesauce105?consumer_key=8bcccc3476eaa137a084c9f0c041915f')
.on('200', function(res) {
var followersCount = res.followers_count;
Object.keys(abbrev).map(function(k) {
k = +k;
if (followersCount > k) {
var a = followersCount / k,
short = a.toString().length > 3 ? Math.round(a * 10) / 10 : a;
followersCount = short + abbrev[k];
}
});
if (followersCount !== undefined) {
$(".card .count").text(followersCount);
$(".card").addClass("visible");
}
})
.go();
var audio = new Audio('file:///home/chronos/u-95bb3831b1fe3a2c6fb7e71045f629e9434b1484/Downloads/html%205%20up/echoed-ding.mp3');
function playMyAudio() {
audio.play()
}
var x = document.getElementById("myAudio");
function playAudio() {
x.play();
}
function pauseAudio() {
x.pause();
}
function wright(){
document.getElementById("demo").innerHTML = ;
}
My goal is to ring a notification when I hit 1K follows I have a mp3 located on my chromebook at file:///home/chronos/u-95bb3831b1fe3a2c6fb7e71045f629e9434b1484/Downloads/html%205%20up/echoed-ding.mp3
and I am trying to get it to play a couple of times so I can celebrate. I do not know how to check the amount of followers I have so I used code from someone else but since I did not make it I do not know what is happening in the JavaScript department and thus I cannot just figure it out on my own because I normally would just look up how to run a function when a variable hits a certain variable... and in turn would activate the x.play() to play the sound... if you have any suggestions please let me know thanks!
You can use Soundcloud's Javascript SDK to tap into their API from the client. So add this to your HTML:
<script src="https://connect.soundcloud.com/sdk/sdk-3.1.2.js"></script>
<script>
SC.initialize({
client_id: 'YOUR_CLIENT_ID' // edit this with your API credential
})
</script>
Unfortunately, there's no way to receive a "notification" from Soundcloud's API when your followers hit a certain number. Instead, you can write a function that looks up the user periodically, and do something special when the follower count is where you want it. So in your Javascript, something like:
function pollSoundcloud (interval) {
var timer = setInterval(function () {
SC.get('/user/YOUR_USER_ID').then(function (user) {
if (user.followers_count >= 1000) {
clearInterval(timer)
alert('You just reached 1000 followers!') // or do something else
}
})
}, interval)
}
pollSoundcloud(10000) // will check every 10 seconds

Timer is not counting down in Fixed position

I am developing one game app in HTML5 for android devices. In that game I am using simple count down method with setInterval method and I am displaying that counter in timer div. When I make div element position is fixed then count down is not running whenever I touched the screen then only count down starts and stops. BUT this is running good in absolute position, I don't want to make that div as absolute. I have tried all the possibilities, No luck
Please any one help me to resolve this problem
Here is my code
HTML:
<div id="time">
<p id="txt2"></p>
</div>
CSS:
#time {
right: 150px;
top: 11px;
z-index: 999;
position: fixed;
font-size: 30px;
color: rgb(0, 0, 0);
font-weight: bold;
font-size: 30px;
color: #FFFFFF;
}
JS:
function timedCount(){
sec = 119 - c;
document.getElementById("txt2").innerHTML = sec;
c=c+1;
tt=setTimeout(function(){
timedCount()
},10000);
}
function doTimer(){
//alert("TImer starts");
if (!timer_is_on){
timer_is_on=1;
timedCount();
}
}
function stopCount(){
//alert("Timer stops");
clearTimeout(tt);
timer_is_on=0;
//c = 0;
}
Please check this one I refered http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_stop
Try this one with jquery
<!DOCTYPE html>
<html>
<head>
<style>
#time {
right: 150px;
top: 11px;
z-index: 999;
position: fixed;
font-size: 30px;
color: rgb(0, 0, 0);
font-weight: bold;
font-size: 30px;
color: red;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
var c=1, timer_is_on = 0, tt;
$(document).ready(function(){
doTimer();
function doTimer() {
if (!timer_is_on){
timer_is_on=1;
timedCount();
}
}
function timedCount() {
var sec = 119 - c;
$("#txt2").html(sec);
//alert(c);
c = c + 1;
tt = setTimeout(function () {
timedCount()
}, 10000);
}
function stopCount() {
//alert("Timer stops");
clearTimeout(tt);
timer_is_on = 0;
//c = 0;
}
});
</script>
</head>
<body>
<div id="time">
<p id="txt2"></p>
</div>
</body>
</html>
Check this link

Categories

Resources