Can't clearInterval when setInterval is set in an object - javascript

I'm having trouble stoping the interval with clearInterval when the value reaches 100. It reaches a 100 and then keeps on executing the setInterval. Can anybody tell me what i'm doing wrong? Appreciate for your help.
i've provided a link to jsfiddle. Open console.log to see the incrementation. https://jsfiddle.net/netzsqx4/
let values = [[]]
let Circle_1 = {
procent:values[0][0],
startFrom:0,
incrementBy:0,
start: null,
intervalIdAtStart: function(){this.start= setInterval(function(){drawCircle.call(Circle_1)},500)},
clear: function() {
clearInterval(this.start);
}
}
function drawCircle(inputValues){
if(this.startFrom<this.procent){
console.log('draw <', this.procent + " " + this.startFrom)
this.startFrom++
}
else if(this.startFrom>this.procent){
console.log('draw >', this.procent + " " + this.startFrom)
this.startFrom--
}
else{
console.log('else', this.procent + " " + this.startFrom)
this.clear;
}
};
function Http(){
let output = 100
loadoutput(output)
function loadoutput(input){
console.log(input)
values = [
[input],
]
Circle_1.procent=values[0][0]
Circle_1.intervalIdAtStart()
}
}
function getValues(){
Http();
}
setTimeout(getValues,1000);

It was this.clear but it should be this.clear(). This resolved my problem.

Related

If check / check if property exists not working

I have been trying to make a debounce system that is ID based using unix timestamp i want it to print passed if it hasn't been called at all in the past second if it has print failed(with that specific id)
I can't figure out what exactly is going wrong i've tried everything I can imagine
I have recreated the problem in a testfile i've pasted the code below
const Cooldowns = {}
function Test(ID) {
const CurrentDate = Date.now();
let IsReal = false;
if (Cooldowns[ID]) {
IsReal = true;
};
console.log(Cooldowns[ID])
console.log(IsReal)
if (Cooldowns[ID] < CurrentDate || !(IsReal)) {
Cooldowns[ID] = CurrentDate + 1;
console.log(ID + " Time " + CurrentDate + " Passed");
} else {
console.log(ID + " Time " + CurrentDate + " Failed");
};
}
Test(12);
Test(19);
setTimeout(() => {
console.log("----------------------------------------------------");
Test(12);
Test(19);
Test(2);
setTimeout(() => {
console.log("-----------------------------------------------------");
Test(12);
Test(19);
Test(2);
}, 500);
}, 1050);

How to loop a function in Javascript?

I am trying to create a countdown with JQuery. I have different times in an array. When the first time ist finished, the countdown should count to the next time in the array.
I try to do this with the JQuery countdown plugin:
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
var i = 0;
while (i < time.length) {
var goal = date + " " + time[i];
$("#countdown")
.countdown(goal, function(event) {
if (event.elapsed) {
i++;
} else {
$(this).text(
event.strftime('%H:%M:%S')
);
}
});
}
This does not work... But how can i do this?
You should never use a busy wait especially not in the browser.
Try something like this:
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
var i = 0;
var $counter = $("#countdown");
function countdown() {
var goal = date + " " + time[i];
$counter.countdown(goal, function(event) {
if (event.elapsed) {
i++;
if (i < time.length) {
countdown();
}
} else {
$(this).text(
event.strftime('%H:%M:%S')
);
}
});
}
You can't use while or for loop in this case, because the operation you want to perform is not synchronous.
You could do for example something like this with the helper (anonynous) function:
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
var i = 0;
(function countdown(i) {
if (i === time.length) return;
var goal = date + " " + time[i];
$("#countdown")
.countdown(goal, function(event) {
if (event.elapsed) {
countdown(i++);
} else {
$(this).text(event.strftime('%H:%M:%S'));
}
});
})(0)
You need to restart the countdown when the previous one finishes, at the minute you're starting them all at the same time.
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
function startCountdown(i) {
if(i >= i.length) {
return;
}
var goal = date + " " + time[i];
$("#countdown")
.countdown(goal, function(event) {
if (event.elapsed) {
startCountdown(i++);
} else {
$(this).text(
event.strftime('%H:%M:%S')
);
}
});
}
startCountdown(0);

Stop function from re- executing for one second with settimeout

I want to prevent my function from re-executing for one second after it's last executed. I've tried the method below, but it doesn't work.
function displayOut() {
// images
document.getElementById("imgBox").style.backgroundImage = "url(" + db.rooms[roomLoc].roomImg + ")";
// Diologue box
diologueBox.innerHTML = ""; // Clear Box
teleTyperDiologue(db.rooms[roomLoc].description +
" The room contains: " +
(function() {
let x = "";
for (let i = 0; i < db.items.length; i++) {
if (db.items[i].location === roomLoc && db.items[i].hidden === false) {
x += db.items[i].name + ", "
}
}
x = x.slice(0, x.length -2);
if (x === "") {
x = " nothing of special interest";
}
return x;
})()
+ ".");
pause();
};
function pause() {
setTimeout(function() {
// Wait one second!
}, 1000);
}
You could use a pattern like this:
var executing = false;
function myFunc() {
if(!executing) {
executing = true;
//Code
console.log('Executed!');
//End code
setTimeout(function() {
executing = false;
}, 1000);
}
}
setInterval(myFunc, 100);
So in your case, this would look like this:
var executing = false;
function displayOut() {
if(!executing) {
executing = true;
// images
document.getElementById("imgBox").style.backgroundImage = "url(" + db.rooms[roomLoc].roomImg + ")";
// Diologue box
diologueBox.innerHTML = ""; // Clear Box
teleTyperDiologue(db.rooms[roomLoc].description +
" The room contains: " +
(function() {
let x = "";
for (let i = 0; i < db.items.length; i++) {
if (db.items[i].location === roomLoc && db.items[i].hidden === false) {
x += db.items[i].name + ", "
}
}
x = x.slice(0, x.length -2);
if (x === "") {
x = " nothing of special interest";
}
return x;
})()
+ ".");
setTimeout(function() {
executing = false;
}, 1000);
}
};
Try to use throttle (http://underscorejs.org/#throttle) or debounce (http://underscorejs.org/#debounce) from underscore, one of those should fit your needs
This one will achieve that:
function run () {
console.log('Im running');
pause(1000);
};
function pause(s) {
console.log('Im paused');
setTimeout(() =>{
run();
}, s)
};
run();
The code above will run every 1 sec but if you want to make sure the function cant be runned again until you decide then you could use a flag instead like:
let canExecute = true;
function run () {
if (canExecute) {
console.log('Im running');
canExecute = false;
pause(1000);
}
};
function pause(s) {
console.log('Im paused');
setTimeout(() =>{
canExecute = true;
}, s)
};
run();
run();
run();
setTimeout(() =>{
run();
}, 2000)
This code will execute run function twice, first on time and then one more after 2 sec.

How to terminate endless while loop via setTimeout in Javascript

I have a piece of code with while loop which I would like to stop by setTimeout(). But it seems like a endless loop, which never triggers setTimeout(). If I remove while loop, timeout triggers correctly. What is wrong please?
$(document).ready(function()
{
var i = 0, s = false;
setTimeout( function()
{
s = true;
console.log( "Timeuot!!!" );
console.log( "s value is " + s );
}, 1000 );
while( s === false )
{
console.log( "this is while and s is " + s );
i++;
}
console.log( "iterations: " + i );
});
JavaScript runs a single event loop. It won't stop in the middle of a function to see if there are any events (such as clicks or timeouts) that would trigger a different function.
In short: It won't run the timed function until the while loop has finished.
To do this sort of thing, you'd normally have an event driven iterator.
var i = 0,
s = false;
setTimeout(function() {
s = true;
console.log("Timeuot!!!");
console.log("s value is " + s);
}, 1000);
next();
function next() {
if (s) {
return done();
}
console.log({
s, i
});
i++;
setTimeout(next, 0);
}
function done() {
console.log("iterations: " + i);
}
As already mentioned the while loop blocks the one and only thread. To let your example do the thing you want, replace the while loop with setInterval(function) like this:
$(document).ready(function()
{
var i = 0, s = false;
setTimeout( function()
{
s = true;
console.log( "Timeout!!!" );
console.log( "s value is " + s );
}, 1000 );
var interval = setInterval(function() {
console.log( "this is while and s is " + s );
i++;
if (s) {
clearInterval(interval);
console.log("i is " + i)
}
}, 100);
});
setTimeout is never called do the the fact that the while never ends and so the even dispatcher is not going to trigger the setTimeout.

Execute a function BEFORE ANY function is executed

What I want to do is to execute a function automatically every time BEFORE ANY function is executed in JS, regardless if it's a custom or native function if possible.
ie.
whatIWant(functionName){
return console.log('called before '+functionName);
}
function blah(){
return console.log('called blah');
}
function meh(){
return console.log('called meh');
}
alert('woot');
blah();
//will output :
//called before blah
//called blah
meh();
//will output :
//called before meh
//called meh
alert();
//will output :
//called before alert
//will pop up dialog: woot
I do not want to do the following:
Function.prototype.onBefore = function(){};
blah.onBefore();
is it even possible to do what I am asking for? any suggestions, read, or w/e?
Thanks in advance.
What about just providing your function as a callback to whatIWant like this:
function whatIWant(fn) {
var fnName = fn.toString();
fnName = fnName.substr('function '.length);
fnName = fnName.substr(0, fnName.indexOf('('));
console.log('called before ' + fnName);
fn();
}
function meh() {
console.log('called meh');
}
function blah() {
console.log('called blah');
}
whatIWant(meh);
whatIWant(blah);
whatIWant(alert)
what do you guys think about this solution? :)
function bleh(){
console.log('exe a');
}
function limitFn(fn,n) {
var limit = n ;
var counter = 1 ;
var fnName = fn.toString();
fnName = fnName.substr('function '.length);
fnName = fnName.substr(0, fnName.indexOf('('));
return function(){
if(counter <= limit) {
console.log(counter + ' call before ' + fnName + ' limit ' + limit);
counter++;
fn();
} else {
console.log('limit of ' + limit + ' exes reached') ;
}
};
}
limited = limitFn(bleh,2);
limited();
limited();
limited();
limited();

Categories