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

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

Related

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

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.

How can I set timers in slideshow to show as selected?

I have to create a slideshow, using an array of images and have that set on a timer. There is a drop-down menu with slow, medium, and fast options and the pictures need to transition with accordance to the drop down option selected. Whenever I execute this code in a web browser the code repeats itself, while doubling, as I read the value of i in the console.
I have tried using a while and a do-while loop to have the images on a rotation.
I have also tried putting the if-statements outside and below/above the function.
<script>
var i = 0;
function changeImg(){
if (x == 'slow'){
setInterval("changeImg()", 5000);
} else if (x == 'medium'){
setInterval("changeImg()", 3000);
} else if (x == 'fast') {
setInterval("changeImg()", 1000);
} else {}
while (i < 3){
console.log(i);
document.slide.src = sportsArray[i];
i++;
}
console.log(i);
console.log(sportsArray);
}
</sctipt>
First, I would read up on MDN's docs on setInterval() and clearInterval to fill in the knowledge gaps that lead you to approach the problem this way.
You are recursively calling changeImg() in your code which I believe is causing the issue you describe as:
the code repeats itself, while doubling, as I read the value of i in the console
Also, your while loop will run immediately when calling changeImg() which also does not appear to be desired in this situation.
setInterval() mimics a while loop by nature. There is no need for a while loop in this code. Below is a solution that I hope you can use as a reference. I separated the code to determine the interval into a function the getIntervalSpeed.
function changeImg(x) {
var getIntervalSpeed = function(x) {
if (x === 'slow') {
return 5000;
} else if (x === 'medium') {
return 3000;
} else if (x === 'fast') {
return 1000;
} else {
return 3000;
// return a default interval if x is not defined
}
};
var i = 0;
var slideShow = setInterval(function() {
if (i >= sportsArray.length) {
i = 0; // reset index
}
document.slide.src = sportsArray[i]; // set the slide.src to the current index
i++; // increment index
}, getIntervalSpeed(x));
// on click of ANY button on the page, stop the slideshow
document.querySelector('button').addEventListener('click', function() {
clearInterval(slideShow);
});
}

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

Throttle event calls in jQuery

I have a keyup event bound to a function that takes about a quarter of a second to complete.
$("#search").keyup(function() {
//code that takes a little bit to complete
});
When a user types an entire word, or otherwise presses keys rapidly, the function will be called several times in succession and it will take a while for them all to complete.
Is there a way to throttle the event calls so that if there are several in rapid succession, it only triggers the one that was most recently called?
Take a look at jQuery Debounce.
$('#search').keyup($.debounce(function() {
// Will only execute 300ms after the last keypress.
}, 300));
Here is a potential solution that doesn't need a plugin. Use a boolean to decide whether to do the keyup callback, or skip over it.
var doingKeyup = false;
$('input').keyup(function(){
if(!doingKeyup){
doingKeyup=true;
// slow process happens here
doingKeyup=false;
}
});
You could also use the excellent Underscore/_ library.
Comments in Josh's answer, currently the most popular, debate whether you should really throttle the calls, or if a debouncer is what you want. The difference is a bit subtle, but Underscore has both: _.debounce(function, wait, [immediate]) and _.throttle(function, wait, [options]).
If you're not already using Underscore, check it out. It can make your JavaScript much cleaner, and is lightweight enough to give most library haters pause.
Here's a clean way of doing it with JQuery.
/* delayed onchange while typing jquery for text boxes widget
usage:
$("#SearchCriteria").delayedChange(function () {
DoMyAjaxSearch();
});
*/
(function ($) {
$.fn.delayedChange = function (options) {
var timer;
var o;
if (jQuery.isFunction(options)) {
o = { onChange: options };
}
else
o = options;
o = $.extend({}, $.fn.delayedChange.defaultOptions, o);
return this.each(function () {
var element = $(this);
element.keyup(function () {
clearTimeout(timer);
timer = setTimeout(function () {
var newVal = element.val();
newVal = $.trim(newVal);
if (element.delayedChange.oldVal != newVal) {
element.delayedChange.oldVal = newVal;
o.onChange.call(this);
}
}, o.delay);
});
});
};
$.fn.delayedChange.defaultOptions = {
delay: 1000,
onChange: function () { }
}
$.fn.delayedChange.oldVal = "";
})(jQuery);
Two small generic implementations of throttling approaches. (I prefer to do it through these simple functions rather than adding another jquery plugin)
Waits some time after last call
This one is useful when we don't want to call for example search function when user keeps typing the query
function throttle(time, func) {
if (!time || typeof time !== "number" || time < 0) {
return func;
}
var throttleTimer = 0;
return function() {
var args = arguments;
clearTimeout(throttleTimer);
throttleTimer = setTimeout(function() {
func.apply(null, args);
}, time);
}
}
Calls given function not more often than given amount of time
The following one is useful for flushing logs
function throttleInterval(time, func) {
if (!time || typeof time !== "number" || time < 0) {
return func;
}
var throttleTimer = null;
var lastState = null;
var eventCounter = 0;
var args = [];
return function() {
args = arguments;
eventCounter++;
if (!throttleTimer) {
throttleTimer = setInterval(function() {
if (eventCounter == lastState) {
clearInterval(throttleTimer);
throttleTimer = null;
return;
}
lastState = eventCounter;
func.apply(null, args);
}, time);
}
}
}
Usage is very simple:
The following one is waiting 2s after the last keystroke in the inputBox and then calls function which should be throttled.
$("#inputBox").on("input", throttle(2000, function(evt) {
myFunctionToThrottle(evt);
}));
Here is an example where you can test both: click (CodePen)
I came across this question reviewing changes to zurb-foundation. They've added their own method for debounce and throttling. It looks like it might be the same as the jquery-debounce #josh3736 mentioned in his answer.
From their website:
// Debounced button click handler
$('.button').on('click', Foundation.utils.debounce(function(e){
// Handle Click
}, 300, true));
// Throttled resize function
$(document).on('resize', Foundation.utils.throttle(function(e){
// Do responsive stuff
}, 300));
Something like this seems simplest (no external libraries) for a quick solution (note coffeescript):
running = false
$(document).on 'keyup', '.some-class', (e) ->
return if running
running = true
$.ajax
type: 'POST',
url: $(this).data('url'),
data: $(this).parents('form').serialize(),
dataType: 'script',
success: (data) ->
running = false

What is the best way to have a function toggle between two different processes?

I have a function that I want it execute alternating processes every time it's triggered. Any help on how I would achieve this would be great.
function onoff(){
statusOn process /*or if on*/ statusOff process
}
One interesting aspect of JavaScript is that functions are first-class objects, meaning they can have custom properties:
function onoff() {
onoff.enabled = !onoff.enabled;
if(onoff.enabled) {
alert('on');
} else {
alert('off');
}
}
For this to work, your function should have a name. If your function is anonymous (unnamed), you can try to use arguments.callee to access it, but that is deprecated in the new ES5 standard and not possible when using its strict mode.
With the use of closures, you can define a static variable that is only accessible by the function itself:
var toggle = (function()
{
var state = true;
return function()
{
if(state)
alert("A");
else
alert("B");
state = !state;
};
})();
Now you can repeatedly invoke toggle(), and it would alternate between "A" and "B". The state variable is unaccessible from the outside, so you don't pollute the global variable scope.
Use closures. In addition to closures, this method demonstrates arbitrary arguments and arbitrary numbers of functions to cycle through:
Function cycler
function cycle() {
var toCall = arguments;
var which = 0;
return function() {
var R = toCall[which].apply(this, arguments);
which = (which+1) % toCall.length; // see NOTE
return R;
}
}
Demo:
function sum(a,b) {return a+b}
function prod(a,b) {return a*b}
function pow(a,b) {return Math.pow(a,b)}
function negate(x) {return -x;}
var f = cycle(sum, prod, pow, negate);
console.log(f(2,10)); // 12
console.log(f(2,10)); // 20
console.log(f(2,10)); // 1024
console.log(f(2)); // -2
// repeat!
console.log(f(2,10)); // 12
console.log(f(2,10)); // 20
console.log(f(2,10)); // 1024
console.log(f(2)); // -2
Arbitrary cycler
Alternatively if you do not wish to assume all cycled things are functions, you can use this pattern. In some ways it is more elegant; in some ways it is less elegant.
function cycle() {
var list = arguments;
var which = 0;
return function() {
var R = list[which];
which = (which+1) % toCall.length; // see NOTE
return R;
}
}
Demo:
var cycler = cycle(function(x){return x}, 4, function(a,b){return a+b});
cycler()(1); // 1
cycler(); // 4
cycler()(1,5); // 6
// repeat!
cycler()(1); // 1
cycler(); // 4
cycler()(1,5); // 6
NOTE: Because javascript thinks 10000000000000001%2 is 0 (i.e. that this number is even), this function must be three codelines longer than necessary, or else you will only be able to call this function 10 quadrillion times before it gives an incorrect answer. You are unlikely to reach this limit in a single browsing session... but who knows
If I'm understanding what you want, this may be what you're looking for:
var AlternateFunctions = function() {
var one = function() {
// do stuff...
current = two;
}, two = function() {
// do stuff...
current = one;
}, current = one;
return function() {
current();
}
}();
Then calling AlternateFunctions(); will cycle between one() and two()
There are a couple of good answers already posted, but I'm wondering what you're trying to achieve. If you're keeping track of some DOM element's state, instead of having state saved within the function, you should check the state of the element so that the function isn't operating in a vacuum (and possibly not doing what you expect). You can check some attribute, e.g., class:
function onoff(obj){
if(obj.className === 'on') {
obj.className = 'off';
}else{
obj.className = 'on';
}
}
var last=0;
function toggle() {
if(last) {
last=0;
// do process 2
}
else {
last=1;
// do process 1
}
}
See jsfiddle demo
var status=true;
function onOff(el){
/*
* toggle
*/
status = (status ? false : true);
status
? el.html('on')
: el.html('off');
}

Categories

Resources