How to create a loop in an interval function (the right way) - javascript

I have been trying to replicate an example of a rotating text, but I wanted to make it infinite. However, I get it just once and I think it might be related with this logic:
Original link:
https://codepen.io/galefacekillah/pen/jWVdwQ
My first attempt, applying the recursion, was based on one example in the Mozilla docs:
let nIntervId;
function checkIntervalFinish() {
if (!nIntervId) {
nIntervId = setInterval(RotateText, 4000);
}
}
function RotateText() {
var visibleWord = document.getElementsByClassName('visible')[0],
nextWord = visibleWord.nextSibling;
if (nextWord.nodeType == 3) nextWord = nextWord.nextSibling;
if (!(nextWord == null)) {
visibleWord.setAttribute('class', 'hidden');
nextWord.setAttribute('class', 'visible');
} else {
clearInterval(nIntervId);
nIntervId = null;
}
}
checkIntervalFinish();
My second attempt was using a setTimeup. I also tried changing directly the setTimeup for the setInterval, but it didn't work. If I put a console.log, the interval function is executed infinitely, however, not this function. Although this works, it just executes once as well.
var test = function () {
// MY FUNCTION
var intervalID = setInterval(function () {
var visibleWord = document.getElementsByClassName('visible')[0],
nextWord = visibleWord.nextSibling;
if (nextWord.nodeType == 3) nextWord = nextWord.nextSibling;
if (!(nextWord == null)) {
visibleWord.setAttribute('class', 'hidden');
nextWord.setAttribute('class', 'visible');
} else {
clearInterval(intervalID);
}
}, 4000)
// END
setTimeout(test, 100);
};
test();
Can someone explain to me what is it that I am doing wrong? Some why, I think it is related to the null validation.

Related

can I call a private function from within the same object javascript

ETA: I don't believe this question is a duplicate to the one linked. I know how to return a private variable (as shown below in the code), this question was about how to call a private function within the same object.
I'm having trouble finding relevant information for javascript specifically. I have an object declared and within that object I have declared four functions (three that are object methods and one that is not).I want to make the fourth one an object method so that I can call it separately from jquery (timer.displayTime(); ) but when I do that startIntervalTimer use of the function stops working. Is what I'm trying to do even possible?
var startStopTime = function() {
//This function is currently called inside startIntervalTimer();
function displayTime() {
//Display correct time
};
//I WANT SOMETHING LIKE THIS INSTEAD BUT (SEE startIntervalTimer)
this.displayTime = function() {
//Display correct time
}
var intervalTimer;
this.startIntervalTimer = function() {
console.log(timeSetMS);
intervalTimer = setInterval(function() {
if(timeSetMS > 0) {
timeSetMS -= 1000;
displayTime(); //THIS IS WHERE AND HOW IT IS CALLED
this.displayTime(); //THIS IS WHAT I'M GOING FOR, BUT IT WON'T WORK
console.log(timeSetMS);
} else if(timeSetMS <= 0) {
clearInterval(intervalTimer);
console.log("timer stopped");
}
}, 1000
);
}
};
and then in the jquery I have:
var timer = new startStopTime();
$("#timer-container, #timer-label").click(function() {
if(power == "off") {
power = "on";
timer.startIntervalTimer();
} else if (power == "on") {
power = "off";
timer.stopTimer();
}
});
//I want to add this, below
$("#session-length").click(function() {
//Change the display
timer.displayTime();
displayTime(); // This won't work obviously because it's out of scope
});
You can declare another variable inside the object, ie. self:
var startStopTime = function() {
//declare self
var self = this;
this.displayTime = function() {
//Display correct time
}
var intervalTimer;
this.startIntervalTimer = function() {
console.log(timeSetMS);
intervalTimer = setInterval(function() {
if(timeSetMS > 0) {
timeSetMS -= 1000;
displayTime();
self.displayTime(); // use self instead
console.log(timeSetMS);
} else if(timeSetMS <= 0) {
clearInterval(intervalTimer);
console.log("timer stopped");
}
}, 1000
);
}
};

Right way to execute all if-bodies on the first method call

I use JavaScript to display a binary clock on a website. When the site is first loaded, the clock needs to be set to the right time and then updated.
What is the right way to get this behaviour? Right now I have a var that is checked on every update and is set to false after the first run.
Would it be better to copy the function, remove the conditions and have it call the other function?
This is the function:
time.firstRun = true;
function updateBinaryClock() {
var now = moment().toObject();
var bin;
if (time.showClockWithSeconds) {
bin = toSixBit(now.seconds.toString(2));
setColor(".binSec", bin);
}
if (now.seconds == 0 || time.firstRun) {
bin = toSixBit(now.minutes.toString(2));
setColor(".binMin", bin);
}
if (now.minutes == 0 || time.firstRun) {
bin = toSixBit(now.hours.toString(2));
setColor(".binHour", bin);
}
if (time.firstRun) {
time.firstRun = false;
}
setTimeout(updateBinaryClock, 0.1 * 1000);
}
Your function will saturate your ram soon, because you forgot to clear timeout on every function execution.
You could use setInterval instead of setTimeout:
function updateBinaryClock() {
aux_updateBinaryClock(true);
setInterval(aux_updateBinaryClock, 100); // 0.1*1000
}
function aux_updateBinaryClock(isFirstRun) {
var now = moment().toObject(),
bin;
if (time.showClockWithSeconds) {
bin = toSixBit(now.seconds.toString(2));
setColor(".binSec", bin);
}
if (now.seconds === 0 || isFirstRun) {
bin = toSixBit(now.minutes.toString(2));
setColor(".binMin", bin);
}
if (now.minutes === 0 || isFirstRun) {
bin = toSixBit(now.hours.toString(2));
setColor(".binHour", bin);
}
}
updateBinaryClock();
Also note that setInterval and setTimeout are inaccurate, there are many more accurate implementations of setInterval and setTimeout (es. this or this)
What I would do is separate it into 2 functions.
function initBinaryClock() {
}
function updateBinaryClock() {
requestAnimationFrame(updateBinaryClock);
}
window.addEventListener("load", function loader(){
window.removeEventListener("load", loader, false);
initBinaryClock();
updateBinaryClock();
}, false);

Make a function only run once (Javascript)

So I'm trying to create a function which changes the 0 slot of an array to an input value. However I want this function to only be able to run once. How do I do this, any help is greatly appreciated thanks.
function submitForm() {
$('#inputForm').submit;
if ($("#inputValue").val() != inputException) {
charSetName();
$("#inputValue").val("");
}
$("#inputValue").val("");
}
function charSetName() {
var nameSet = false;
if (nameSet == false) {
nameSet = true;
charDetails[0] = $("#inputValue").val();
document.getElementById("name").innerHTML = "<li id='name''>Name: " + charDetails[0] + "</li>";
}
}
This is an old question but I was brought here because I needed something similar.
To anyone who comes next time, here was what I eventually did:
I simply declared a variable with an initial count of 0.
Then every time my function runs, it auto increases.
The code I want to run once just checks if the count is 1, then it runs. If not, it doesnt.
Like this:
let count = 0;
count === 1 ? doSomething : doNothing
count++
Does it help?
Try this, I have defined isFunctionCalled:Boolean variable for handle it.
var isFunctionCalled = false;
function submitForm() {
$('#inputForm').submit;
if ($("#inputValue").val() != inputException) {
if (!isFunctionCalled) {
charSetName();
}
$("#inputValue").val("");
}
$("#inputValue").val("");
}
function charSetName() {
var nameSet = false;
if (nameSet == false) {
nameSet = true;
charDetails[0] = $("#inputValue").val();
document.getElementById("name").innerHTML = "<li id='name''>Name: " + charDetails[0] + "</li>";
}
isFunctionCalled = true;
}
Mind the executed variable:
var something = (function() {
var executed = false;
return function () {
if (!executed) {
executed = true;
// do something
}
};
})();
There are a lot of ways to do this.
Just a simple way is to set a flag value.
if(flag){
//your code here...
flag = !flag;
}
SO, if the value of the flag is 1 at first it will work. Then as the flag value is changed to 0, then the next time it is called, it will not be invoked, as flag is 0.

I want to not be able to run the same command twice very quickly

So I have this chunk of code here:
lockskipCommand = (function(_super) {
__extends(lockskipCommand, _super);
function lockskipCommand() {
return lockskipCommand.__super__.constructor.apply(this, arguments);
}
lockskipCommand.prototype.init = function() {
this.command = '/lockskip';
this.parseType = 'exact';
return this.rankPrivelege = 'bouncer';
};
lockskipCommand.prototype.functionality = function() {
data.lockBooth();
new ModerationForceSkipService();
return setTimeout((function() {
return data.unlockBooth();
}), 4500);
};
return lockskipCommand;
})(Command);
I want to be able to let it has some sort of cool down, so it can't be used quickly in a row. The reason I want this is to prevent from people being skipped, because that's what this chunk of code is for skipping people.
I hope this is enough information to get some help. Thanks!
You can use Underscore's debounce() method (with true as the third argument).
If you don't want to include Underscore for this simple task, you could do...
var debounceFn = function (fn, delay) {
var lastInvocationTime = Date.now();
delay = delay || 0;
return function () {
(Date.now() - delay > lastInvocationTime) && (lastInvocationTime = Date.now()) && fn && fn();;
};
};
jsFiddle.
What I need is a way to not be able to execute the command more than once in a row.
You could do something similar...
var onceFn = function (fn) {
var invoked = false;
return function () {
! invoked && (invoked = true) && fn && fn();
};
};
jsFiddle.

Not doing anything for the first time running the function in javascript /jquery

The problem is I need to break the function if it is first time running
is there any function available , or I have to do something like the following?
var times = 1
function abc () {
if (times == 1)
break;
else
.....
times++;
}
times = 0;
Thanks.
You can use this pattern:
function abc() {
if (!abc.flag) {
abc.flag = true;
return;
}
// .. rest of the code
}
It's based on the fact that Function is also an object in Javascript.
Basically this is a Memoization pattern. It has disadvantage that the flag property can be overwritten by another code. The advantage is that you don't need to pollute global scope with additional variables.
thg435 proposed much more elegant solution.
It appears to me that you're trying to solve the problem in the wrong place. Can you tell us the whole story?
In the meantime, something like this should do the trick:
function abc() {
abc = function() {
// ...actual work...
}
}
Details depend on how your function is defined (globally, locally, as a method).
var isFirstTime = true;
function abc () {
if (isFirstTime)
{
isFirstTime = false;
return;
}
.....
}
abc(); //returns
abc(); //runs
var firstTime= true
function abc () {
if (firstTime)
{
firstTime = false;
return;
}
else
{
.....
}
}
Try This :
var times = 1;
function abc () {
if (times == 1){}
else{
.....
times == 0;}
}

Categories

Resources