clearInterval is not clearing - javascript

Take a look at the function below, It purpose is to change the button text
to "Abort", "Abort 0", "Abort 1" and so on.
Once the counter reaches 10 another function should be executed, but if
the button is clicked, the counter should stop, and the button text should return
to it's original value ("Sync DB").
It seems I'm trying to clear out the interval in a wrong way.
Any assistance will be appreciated.
function sync_database(abort)
{
if (abort == true) { sync_db_btn.innerHTML = "Sync DB"; return false }
sync_db_btn.innerHTML = "Abort"
var i = 0;
sync_db_btn.addEventListener("click", function() { sync_database(true) } );
var x = setInterval(function() {
if (abort == true) {
clearInterval(x);
}
if (i < 10) {
sync_db_btn.innerHTML = "Abort " + i++;
}
}, 1000);
}

var x;
sync_db_btn.addEventListener("click", function() {
sync_database(true);
clearInterval(x);
} );
function sync_database(abort)
{
if (abort == true) { sync_db_btn.innerHTML = "Sync DB"; return false }
sync_db_btn.innerHTML = "Abort"
var i = 0;
x = setInterval(function() {
if (i < 10) {
sync_db_btn.innerHTML = "Abort " + i++;
}
}, 1000);
}

I think you need something like this:
var sync_db_btn = document.getElementById('but'),
abortSync = -1,
interval,
sync_database = function () {
var i = 0;
abortSync *= -1;
if (abortSync < 0) {
sync_db_btn.innerHTML = 'Sync DB';
clearInterval(interval);
return false;
}
sync_db_btn.innerHTML = 'Abort';
interval = setInterval(function () {
if (i < 10) {
sync_db_btn.innerHTML = 'Abort ' + i++;
} else {
sync_db_btn.innerHTML = 'Sync DB';
clearInterval(interval);
abortSync = -1;
}
}, 1000);
};
sync_db_btn.addEventListener('click', sync_database);
A live demo at jsFiddle.

Related

How do I stop a while loop with a button - JavaScript

Hello guys I'm looking for a solution for this program:
var i = 0;
function timer(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds) {
break;
}
}
}
$w.onReady(function () {
while (i === 0) {
dosomething();
timer(1000);
}
});
export function button5_click(event) {
i = 1;
}
My question is how can I stop this while with that button function?
You can do this way!
var flag = true;
let i = 0;
function loopFunc() {
if (flag == true){
i++;
console.log( `Do something here ${i}` );
setTimeout(loopFunc, 100);
}
}
loopFunc();
function stop(){
flag = false;
}
<button onclick="stop();">Stop Loop</button>
You could have a boolean which is checked if true in the while loop and if it true, the while loop will return. Add in an event listener to make that boolean true on click for the button. Don't forget to make the boolean false at the beginning of your script.
Using your code, you could do this
var stopLoop = false; // Add this to your code
var i = 0;
function timer(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds) {
break;
}
}
}
$w.onReady(function () {
while (i === 0) {
if(stopLoop) break;
dosomething();
timer(1000);
}
});
export function button5_click(event) {
stopLoop = true; // add this to your code
i = 1; // You can comment this out
}

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);
}

Javascript injection add item to basket

I am trying to run this script which effectively goes through a json list that contains url and a size to go to the link set add the item to cart based on size, check if it is in stock or already added. I have got the link and the size searching algorithms work independently but together they seem to not work and I can't figure out why?
var foundall = false;
var copItems = [{
"url": "https://www.supremenewyork.com/mobile/#products/303518/22745",
"size": "Medium"
}];
for (var i = 0; i < copItems.length; i++) {
AddToCart(copItems[i], function(carted) {
console.log(carted);
});
}
function AddToCart(item, callback) {
location.href = item.url;
var counter = 0;
var waitToAppear = setInterval(function() {
if (document.querySelector('#cart-update > span')) {
if (document.querySelector('#cart-update > span').innerHTML == 'remove') {
return callback("failed");
clearInterval(waitToAppear);
} else if (document.querySelector('#cart-update > span').innerHTML == 'sold out') {
copSelectSize(size, function(data) {
return callback(data);
clearInterval(waitToAppear);
});
} else if (document.querySelector('#cart-update > span').innerHTML == 'add to basket') {
copSelectSize(item.size, function(Sized) {
return callback("failed");
clearInterval(waitToAppear);
})
} else {
counter += 1;
if (counter == 5) {
return callback("failed");
clearInterval(waitToAppear);
}
}
}
}, 100);
}
function copSelectSize(size, callback) {
var counter = 0;
var checkExist = setInterval(function() {
if (document.getElementById('size-options').length) {
var sizes = document.getElementById('size-options').options;
var size_id;
for (var i = 0; i < sizes.length; i++) {
if (sizes[i].innerText == '\(Size)') {
size_id = i;
document.getElementById('size-options').selectedIndex = size_id;
document.getElementById('size-options-link').innerHTML = '\(Size)';
if (document.querySelector('#cart-update > span').innerHTML != 'remove') {
document.querySelector('#cart-update > span').click();
return callback("success");
clearInterval(checkExist);
}
var checkExista = setInterval(function() {
if (document.querySelector('#cart-update > span').innerHTML == 'remove') {
checkExista = '';
}
clearInterval(checkExista);
}, 100);
break;
}
}
}
counter += 1;
if (counter == 5) {
return callback("failed");
clearInterval(checkExist);
}
}, 200);
}

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";
}

JS How make that function could not be start earlier than 10 seconds after the previous launch?

function testworking(n){
if(n == 1)
testuser();
else
testconfig();
}
setInterval(function(){testworking(n)}, 1000);
How do I make that function testuser(); could not start earlier than 10 seconds after the previous launch?
P.S.:
an approximate algorithm:
if(n == 1){
if (first run function `testuser()` ||
time after previous run `testuser();` == 10 seound){
testuser();
}
}
Set a flag using a timer:
var is_waiting = false;
function testuser() {
if (!is_waiting) {
//do your stuff here
} else {
alert('You must wait ten seconds before doing this again');
}
is_waiting = true;
setTimeout(function() {is_waiting = false}, 10000);
}
You can do it like this
var i = 0;
function testworking(i){
if(i < 10) {
console.log(i);
} else {
console.log('Here is 10 second');
}
}
setInterval(function(){
i = (i == 10) ? 0 : i;
i++;
testworking(i);
}, 1000);
It's not entirely clear what you're looking for, but here's something that might give you an idea.
var n = 1;
var testUserInterval;
function testworking(n) {
if (n == 1)
testuser();
else
testconfig();
}
function testuser() {
var cnt = 0;
if (testUserInterval == null) {
testUserInterval = setInterval(function() {
document.getElementById("testusercnt").innerHTML = cnt;
cnt += 1;
if (cnt == 10) {
clearInterval(testUserInterval);
testUserInterval = null;
//DO SOMETHING ???
testuser();
}
}, 1000);
}
}
function testconfig() {
document.getElementById("testconfig").innerHTML = n;
}
setInterval(function() {
testworking(n++)
}, 1000);
testuser cnt:<span id="testusercnt"> </span>
<br/>testconfig n: <span id="testconfig"> </span>

Categories