Namespacing in Javascript Classes - javascript

I'm trying to create a timer in Javascript and I have a specific issue with how I'm implementing it.
Right now it's like this
function CountUpTimer(seconds,name,targetId,submitButtonId){
this.time = seconds;
this.currentTime = 0;
this.minutes = Math.floor(seconds/60);
this.submitButtonId = submitButtonId;
this.seconds = seconds - this.minutes*60;
this.currentSeconds = 0;
this.currentMinutes = 0;
this.targetId = targetId;
this.name = name;
this.isPaused = false;
this.init = function(){
setInterval(this.name + ".tick()",1000);
}
this.pause = function(){
this.isPaused = true;
}
this.unpause = function(){
this.isPaused = false;
}
this.tick = function(){
if(this.isPaused == false){
if(this.currentTime <= this.time){
if(this.currentSeconds == 59){
this.currentSeconds = 0;
this.currentMinutes++;
}
this.updateTimer();
this.currentTime++;
this.currentSeconds++;
} else{
this.endTiming();
}
}
}
Now, the problem with this is that I can't dynamically create CountUpTimer objects, because I need to know the name of the variable that I am assigning to that object. Is there some way I can work around this - so let's say something like
setInterval(this.tick(),1000);
?

When using callback, you lose the context at execution.
You should use bind to keep the context.
setInterval(this.tick.bind(this),1000);
More details here

this.init = function(){
var self = this;
setInterval(self.tick(),1000);
}
Keep the reference to original object, because using this in setInterval will be in the wrong object context (document).

You can do:
var self = this;
setInterval(function() {
self.tick()
}, 1000);
Or use Function.bind if you are fine with non-legacy support.

Related

Reset animation to original position using javascript

using the following script i was able to move my picture right when clicked:
<script>
var myTimer = null;
function move(){
document.getElementById("fish").style.left =
parseInt(document.getElementById("fish").style.left)+1+'px';
}
window.onload=function(){
document.getElementById("fish").onclick=function(){
if(myTimer == null){
myTimer = setInterval("move();", 10);
}else{
clearInterval(myTimer);
myTimer = null;
}
}
}
</script>
I am having some trouble reseting the picture to original location without using jQuery.
If anyone can help that would be much appreciated.
If you capture the original position ahead of time you can reset later to the captured value:
var originalPosition = document.getElementById("fish").style.left;
function resetPosition() {
document.getElementById("fish").style.left = originalPosition;
}
Use external JavaScript. Some code to look at:
var pre = onload, E, doc, bod;// previous onload
onload = function(){
if(pre)pre();
doc = document; bod = doc.body;
E = function(id){
return doc.getElementById(id);
}
var fish = E('fish'), timer;
fish.onclick = function(){
if(!timer){
timer = setInterval(function(){
fish.style.left = parseInt(fish.style.left)+1+'px';
}, 10);
}
else{
clearInterval(timer); timer = false;
fish.style.left = '0'; // change '0' to what your CSS `left:`value is
}
}// end load
This should work fine,
var myTimer = null;
var startX = 0;
function move(){
document.getElementById("fish").style.left =
parseInt(document.getElementById("fish").style.left)+1+'px';
}
window.onload=function(){
document.getElementById("fish").onclick=function(){
if(myTimer == null){
startX = document.getElementById("fish").style.left;
myTimer = setInterval("move();", 10);
}else{
clearInterval(myTimer);
myTimer = null;
document.getElementById("fish").style.left = startX + "px";
}
}
}

How to pass unspecified number of parameters to setInterval

I need to create an interval wrapper to track if it has been cleared.
The number of parameters to pass to the interval callback should be variable. So this is the code (not working) I implemented to test it:
function MyInterval() {
var id = setInterval.apply(this, arguments); // NOT VALID!!
this.cleared = false;
this.clear = function() {
this.cleared = true;
clearInterval(id);
};
}
var x = 2;
var y = 3;
var fn = function() {
x = x + y;
console.log(x);
};
var interval = new MyInterval(fn, 5000, x, y);
Within the call to setInterval, this must refer to the global object, so instead of this, you want window in your constructor:
var id = setInterval.apply(window, arguments);
// here -------------------^
(or in loose mode you could use undefined or null.)
Then it works, at least on browsers where setInterval is a real JavaScript function and therefore has apply:
function MyInterval() {
var id = setInterval.apply(window, arguments);
this.cleared = false;
this.clear = function() {
this.cleared = true;
clearInterval(id);
};
}
var x = 2;
var y = 3;
var fn = function() {
x = x + y;
log(x);
};
var interval = new MyInterval(fn, 500, x, y);
setTimeout(function() {
interval.clear();
}, 3000);
function log(msg) {
var p = document.createElement('p');
p.appendChild(document.createTextNode(msg));
document.body.appendChild(p);
}
Note, though, that host-provided functions are only required to be callable, they are not required to inherit from Function.prototype and so they're not required/guaranteed to have apply. Modern browsers ensure they do, but earlier ones (IE8, for instance) did not. I can't speak to how well-supported apply is on setInterval.
If you need to support browsers that may not have it, just to use your own function:
function MyInterval(handler, interval) {
var args = Array.prototype.slice.call(arguments, 2);
var tick = function() {
handler.apply(undefined, args);
};
var id = setInterval(tick, interval);
this.cleared = false;
this.clear = function() {
this.cleared = true;
clearInterval(id);
};
}
This also has the advantage that it works even on browsers that don't support additional args on setInterval (fairly old ones).
Example:
function MyInterval(handler, interval) {
var args = Array.prototype.slice.call(arguments, 2);
var tick = function() {
handler.apply(undefined, args);
};
var id = setInterval(tick, interval);
this.cleared = false;
this.clear = function() {
this.cleared = true;
clearInterval(id);
};
}
var x = 2;
var y = 3;
var fn = function() {
x = x + y;
log(x);
};
var interval = new MyInterval(fn, 500, x, y);
setTimeout(function() {
interval.clear();
}, 3000);
function log(msg) {
var p = document.createElement('p');
p.appendChild(document.createTextNode(msg));
document.body.appendChild(p);
}
You might be tempted to use the new ES2015 spread operator:
var id = setInterval(...arguments);
...but note that if you transpile (and right now you'd have to), it ends up being an apply call, and so you have the issue of whether apply is supported.
I suggest that you pass an "options" parameter to your timeout.
var MyInterval = (function(window) {
return function(callbackFn, timeout, options) {
var id = setInterval.apply(window, arguments);
this.cleared = false;
this.clear = function() {
this.cleared = true;
clearInterval(id);
};
}
}(window));
var fn = function(opts) {
opts.x += opts.y;
console.log('x = ', opts.x);
};
var opts = {
x: 2,
y: 3
};
var ms = 5000;
var interval = new MyInterval(fn, ms, opts);
// Bootstrap a custom logger. :)
console.log = function() {
var logger = document.getElementById('logger');
var el = document.createElement('LI');
el.innerHTML = [].join.call(arguments, ' ');
logger.appendChild(el);
logger.scrollTop = logger.scrollHeight;
}
body{background:#7F7F7F;}h1{background:#D7D7D7;margin-bottom:0;padding:0.15em;border-bottom:thin solid #AAA;color:#444}#logger{height:120px;margin-top:0;margin-left:0;padding-left:0;overflow:scroll;max-width:100%!important;overflow-x:hidden!important;font-family:monospace;background:#CCC}#logger li{list-style:none;counter-increment:step-counter;padding:.1em;border-bottom:thin solid #E7E7E7;background:#FFF}#logger li:nth-child(odd){background:#F7F7F7}#logger li::before{content:counter(step-counter);display:inline-block;width:1.4em;margin-right:.5em;padding:.25em .75em;font-size:1em;text-align:right;background-color:#E7E7E7;color:#6A6A6A;font-weight:700}
<h1>Custom HTML Logger</h1><ol id="logger"></ol>
I created a utility function rather than a constructor to solve your issue.
function Wrapper(delay) {
var isCleared,
intervalId,
intervalDelay = delay || 5e3; // default delay of 5 sec
function clear() {
if (!isCleared) {
console.log('clearing interval');
isCleared = true;
clearInterval(intervalId);
}
}
function setUpInterval(callback){
var params = [].slice.call(arguments, 1);
if (!callback) {
throw new Error('Callback for interval expected');
}
params.unshift(intervalDelay);
params.unshift(callback);
intervalId = setInterval.apply(null, params);
}
return {
setUp : setUpInterval,
clear : clear
}
}
function intervalCallback() {
console.log([].slice.call(arguments).join(','));
}
var wrapper = Wrapper(1e3); // create wrapper with delay for interval
console.log('test case 1');
wrapper.setUp(intervalCallback, 'params', 'to', 'callback');
// call clear interval after 10sec
setTimeout(function() {
wrapper.clear();
}, 10e3);
Hope this helps.

Javascript element.style.opacity is undefined. Why?

I am trying to make a JS function that flickers an element. I use a setInterval() for timing, but it gives the error message Uncaught TypeError: Cannot read property 'opacity' of undefined.
When I try to modify the opacity not with a timer, but "by hand", that works...
What am I doing wrong?
Usage:
document.getElementById('idOfTheElement').startFlicker();
The function:
Element.prototype.startFlicker = function() {
var blinkInterval = setInterval(function() {
if (parseInt(this.style.opacity) === 0) {
this.style.opacity = 1;
} else {
this.style.opacity = 0;
}
}, 50);
};
Try this
Element.prototype.startFlicker = function() {
var self = this;
var blinkInterval = setInterval(function() {
if (parseInt(self.style.opacity) === 0) {
self.style.opacity = 1;
} else {
self.style.opacity = 0;
}
}, 50);
};
In setInterval this refers to window, you need store context (this - current element) in variable and use in setInterval
Because of the context. this.style inside the setInterval refers to the global window object.
You could always make a reference to the element itself, because inside the setInterval function, the window object is passed as this.
Instead, you should give .bind() a try. So this will be a reference to the argument of the method.
Element.prototype.startFlicker = function() {
var blinkInterval = setInterval(function() {
if (parseInt(this.style.opacity) === 0) {
this.style.opacity = 1;
} else {
this.style.opacity = 0;
}
}.bind(this), 50);
};

setInterval() with a count

If possible I'd like to use to remove count and use an argument in self.addOrbitTrap(). At the moment for testing my code does something like this:
Bbrot.prototype.findMSet = function() {
//...code
var self = this;
canvasInterval = setInterval(function() {
self.addOrbitTrap();
}, 0);
}
var count = 0;
Bbrot.prototype.addOrbitTrap = function() {
//...code
if (count === 100) {
// Call a different function. That's why I use count
}
count++;
}
Edit: To be more specific, count is used in my code to count how many times addOrbitTrap() successfully runs (it does not add an orbit trap if a randomly selected pixel is a part of the Mandelbrot Set). After it runs some number of times, I call a different function (from within addOrbitTrap()). I would rather not use a global variable because count is not used anywhere else.
You could introduce count as a local variable inside findMSet that you pass to addOrbitTrap(); at each interval the value will be increased:
Bbrot.prototype.findMSet = function() {
//...code
var self = this,
count = 0;
canvasInterval = setInterval(function() {
self.addOrbitTrap(++count);
}, 0);
}
Handling the value is simple:
Bbrot.prototype.addOrbitTrap = function(count) {
//...code
if (count === 100) {
// Call a different function. That's why I use count
}
}
just make the variable on the object and use it.
Bbrot.prototype.count = 0;
Bbrot.prototype.findMSet = function() {
//...code
var self = this;
canvasInterval = setInterval(function() {
self.addOrbitTrap();
}, 0);
}
Bbrot.prototype.addOrbitTrap = function() {
if(ranSuccessful)
this.count++;
}
Bbrot.prototype.someOtherFunc = function() {
return this.count;
}

problem with simple tween class in javascript

I'm trying to build a simple Tween class in javascript. The code reads something like:
function Tween(object, parameters) { // constructor-class def.
this.object = object;
this.parameters = parameters;
this.isRunning = true;
this.frameRate = some value;
this.timeElapsed = some value;
this.duration = some value;
}
Tween.prototype.drawFrame = function () {
var self = this;
this.nextFrame();
if (this.isRunning)
setTimeout( function () { self.drawFrame() } , 1000 / frameRate);
}
Tween.prototype.nextFrame = function () {
if (this.timeElapsed < this.duration) {
// calculate and update the parameters of the object
} else
this.isRunning = false;
}
Tween.prototype.start = function () {
this.isRunning = true;
this.drawFrame();
}
This is then called by another script, say main.js :
window.onload = init;
init = function() {
var tweenDiv = document.createElement('div');
tweenDiv.id = 'someDiv';
document.body.appendChild(tweenDiv);
var myTween = new Tween(document.getElementById('someDiv').style, 'left', parameters);
myTween.start();
}
Unfortunately, this doesnt work. If I examine my site with Google Chrome developer tools, someDiv has its left-style-attribute set to the number of pixels set in the parameters. But it doesn't move on the screen.
Anybody know what I'm doing wrong? Why isn't someDiv being redrawn?
Much Obliged
You have to set the position style to absolute, fixed or relative for the left style to have any effect.

Categories

Resources