SetInterval slowing down - javascript

After finding out I cannot use vender prefixes in Javascript, I tried to make my own fade-to-blur. After about 5-10 seconds of the script running the console.log calls slow to around one per second. Is this something on my end?
Here's the code I've made
var i = 0;
var iv = setInterval(function(){
if(Number(i) > 2)
{
clearInterval(iv);
}
console.log(i);
r = i.toFixed(2);
$('#r').css('filter', 'blur(' + r + 'px)');
$('#r').css('-webkit-filter', 'blur(' + r + 'px)');
$('#r').css('-moz-filter', 'blur(' + r + 'px)');
$('#r').css('-o-filter', 'blur(' + r + 'px)');
$('#r').css('-ms-filter', 'blur(' + r + 'px)');
i += 0.01;
}, 1);
And a JSFiddle
I'm guessing it's the way JS deals with floating-point numbers, also is there any way to get the fade to blurry more smooth? It's quite jumpy once i gets to around 0.8. How do I fix the second delay on the setInterval? Can anyone else reproduce this?
Things to note
The same thing occurred while trying to do the same with a for-loop, but it also rendered the page useless until it got to 2 when the loop stopped.

You can make the script faster by caching the calculation of the string 'blur(' + r + 'px)' into a javascript variable and save unwanted calculation.
You can also cache the $('#r') object into a javascript variable or even use the jquery css multiple-word properties: $('#r').css({propertyName : value , propertyName : value})
Something like:
var calc = 'blur(' + r + 'px)';
$('#r').css({
'filter' : calc ,
'-webkit-filter' : calc,
'-moz-filter' : calc,
'-o-filter' : calc,
'-ms-filter' : calc
});
check it here: http://jsfiddle.net/gMq3P/3/

Related

Print out math expression contained within variable

not really sure this is possible, cant seem to find any answers that cover it.
Ive found questions on running a math expression that's given as a string and they do the opposite of what im looking for.
basically im debugging my code and want to print out what the expression is to the console. There are currently 30 calculations in various expressions that run each time the code executes and the number is growing.
EG:
var equation = (1 + 5) * (21 x 7);
Ive simplified it as there are variables that are actually parsed for the output.
I want to out put the expression as a string running the calculation but also keep the calculation running for the application.
I am currently concatenating strings and its tedious work so I hoped there might be a better solution than this: as you should see, i do need the variables to work as expected but not the whole expression, thus giving the simplified more readable result above.
This works with varuns answer but not in my case see update below:
var printout = '(' +var1+ ' + ' +var2+ ') * (' +var3+ ' * ' +var4+ ')';
Update based upon Varun's Answer & Comments below it:
var array = [1, 5, 21, 7];
var printout = '(' +array[0]+ ' + ' +array[1]+ ') * (' +array[2]+ ' * ' +array[0]+ ')';
I guess below is the code you are looking for
var eq = `(1 + 5) * (21 * 7)`;
console.log( eq + ' = ' + eval(eq) )
You can also enhance it like this for more dynamic content
var array = [1, 5, 21, 7];
var inp1 = array[0]
var inp2 = array[1]
var inp3 = array[2]
var inp4 = array[3]
var addOperand = "+"
var multiplyOperand = "*"
var eq = `(${inp1} ${addOperand} ${inp2}) ${multiplyOperand} (${inp3} ${multiplyOperand} ${inp4})`;
console.log( eq + ' = ' + eval(eq) )
Since you are using arrays, this is seems scalable and efficient
var array = ['(',1, '+', 5,')', '*','(', 21,'*', 7,')'];
eq = array.join(' ')
console.log( eq + ' = ' + eval(eq) )
Could be more generic but not sure if you need that much only for testing,
here your equation can be any string.
lineNo is the lineNo of your equation inside the function
function calculate(x, y) {
var equation = (x + 5) * (y * 7);
let lineNo = 1
console.log(arguments.callee.toString().split('\n\t')[lineNo].replace(/x/g, x).replace(/y/g, y))
}
calculate(3, 4)

Jquery progressbar random image width

I really don't know what im doing wrong. I want to change the width of the image to a random number from 0 - 100%. Can someone tell me what i'm doing wrong?
function progress(){
$("body").append("<div class='main_div'></div>");
var x = Math.floor(Math.random() * 10) + 1;
var x = 5;
for(var i = 0; i < x; i++){
$(".main_div").append("<div class='statusbar'></div>");
$(".statusbar:nth-child(" + x + ")").append("<img src='project_status.gif'>");
var c = Math.floor(Math.random() * 100) + 1;
$(".statusbar:nth-child(" + x + ") img").css({ "width", "(" + c +")%" });
}
}
There are errors in your Math.floor() function: Instead of
Math.floor(Math.random() * 10) + 1;
It should be
Math.floor((Math.random() * 10) + 1));
with the +1 within the Math.floor brackets.
I don't know if it would be helpful or not, but I have previously produced a random-size progress bar here: http://jsfiddle.net/cu22W/10/
The issue is with this statement:
$(".statusbar:nth-child(" + x + ") img").css({ "width", "(" + c +")%" });
You should read up on JQuery .css() function : http://api.jquery.com/css/
But when you use the .css() function with { } brackets the syntax is the same as CSS itself.
So for your statement the proper way would be :
.css({ width : c +"%" })
or, if you wanted to keep it the way you have it just remove the { } brackets :
.css( "width", c +"%")
I am also pretty sure you don't need to wrap c in ()

how can render html tags in html5 canvas filltext() method?

how can render HTML tags in html5 canvas filltext() method?
for example here is the rest of the code:
context.fillText(
"label: " + "hossein" + "<br/>" + "id: " + "52" + "<br/>",
Math.round(node[prefix + 'x'] + size + 10),
Math.round(node[prefix + 'y'] - 60)
);
is correct the <br> html tag that I use in code? does it work correct?
if not how must I use that?
The fillText() method can only take plain text and doesn't parse any tags within it. If your text is as simple as here you can however make your own parser.
function myFillText(txt, x, y) {
// get a pseudo height for the font
var fontParts = context.font.split(' '),
fontHeight = parseInt(fontParts.length === 2 ? fontParts[0] : fontParts[1], 10),
// split the text based on HTML5 line-breaks
txtParts = txt.split('<br>'),
i = 0;
// iteate parts and increase line position for each line
for(; i < txtParts.length; i++) {
context.fillText(txtParts[i], x, y + i * fontHeight);
}
}
Now simply use this instead:
myFillText("label: " + "hossein" + "<br>" + "id: " + "52" + "<br>",
Math.round(node[prefix + 'x'] + size + 10),
Math.round(node[prefix + 'y'] - 60));
Online demo
PS: if you're using HTML5 then you can use <br> without the back-slash. The back-slash is for XHTML - or modify the parser to support the other form.
You can't use html tags inside Canvas. Canvas has its own set of drawing commands.
As you've discovered, one of those drawing commands is fillText.
If you want multi-lines of canvas text, you must do multiple fillText commands and increase the y-coordinate of each succeeding fillText.
var x = Math.round(node[prefix + 'x'] + size + 10);
var y = Math.round(node[prefix + 'y'] - 60);
var myLineHeight=16 // space between lines of text
fillText("label: "+"hossein", x,y);
fillText("id: "+"52", x,y+myLineHeight);
fillText("Other stuff", x,y+myLineHeight*2);
fillText("Even more stuff", x,y+myLineHeight*3);

JQuery Algorithm for changing DIV offset if still in view

hopefully you may be able to assist.
My example code:
http://jsfiddle.net/RevengerTT/YZtyj/1/
I'm trying to work out an algorithm which will capture the offset().left and work out if it has moved the DIV "stretchflex" out of the view state.
I'm really struggling to get my head around this (started JQuery coding today after watching a quick video).
I've worked in three variables I think should give me the values I need, but the issue I'm having is that var z = $("#stretchflex").width() doesn't represent the "actual" width of the DIV, but the visible width of it.
Can anyone see where I'm going wrong?
$("#SFPanLeft").click(function () {
var x = $("#SFHolder").width()
var y = $("#stretchflex").offset().left
var z = $("#stretchflex").width()
$("#x").html("X : " + x.toString());
$("#y").html("Y : " + y.toString());
$("#z").html("Z : " + z.toString());
if (x > (z + y)) { /* <----This is the bit which doesn't work */
var left = $("#stretchflex").offset().left
left -= 176
$("#stretchflex").css({
left: left + 'px'
});
};
});
Many thanks for your help in advance - can't think how many times I've found the answers I need by searching this site :)
Think I've sorted this.
Just in case anyone finds this...
$("#SFPanLeft").click(function () {
var x = $("#SFHolder").width();
var y = $("#stretchflex").offset().left;
var z = $("#stretchflex").get(0).scrollWidth; /* using scrollWidth fixes */
$("#x").html("X : " + x.toString());
$("#y").html("Y : " + y.toString());
$("#z").html("Z : " + z.toString());
if (x < (z + y)) { /* updated algorithm */
var left = $("#stretchflex").offset().left
left -= 176
$("#stretchflex").css({
left: left + 'px'
});
};
});

javascript for loop with decimals

I'm trying to use this for loop in order to show divs. But I get a strange error from the jQuery lib.
Error: Syntax error, unrecognized expression: =10]
I have read about the problems with javascript decimals, but I still can't understand why this won't work:
for (var i = 10.00; i >= ui.value; i -= 0.25) {
$("data_id=" + Math.floor(i) + "]").show();
}
When hiding the divs, I use this and it works fine:
for (var i = 0.00; i < ui.value; i += 0.25) {
$("[data_id=" + Math.floor(i) + "]").hide();
}
You forgot the [ in the first loop, this will work:
for (var i = 10.00; i >= ui.value; i -= 0.25) {
$("[data_id=" + Math.floor(i) + "]").show();
}
You should transform this into an integer loop, if you are .floor()-ing the numbers, anyway.
You're missing your opening square bracket for the attribute equals selector:
for (var i = 10.00; i >= ui.value; i -= 0.25) {
$("[data_id=" + Math.floor(i) + "]").show();
}
As others have mentioned, however, there is absolutely no reason to be using floats for this, since the call to .floor() essentially means you are calling .show() on each of the divs 4 times unnecessarily:
for (var i = 10; i >= ui.value; i--) {
$("[data_id=" + i + "]").show();
}
This should accomplish exactly you want, in about a quarter of the work.
You are missing a [ in your selector here:
$("data_id=" + Math.floor(i) + "]").show();
Which should be:
$("[data_id=" + Math.floor(i) + "]").show();
You should probably add ' around the value of data_id as well, so the final result should be:
$("[data_id='" + Math.floor(i) + "']").show();
You should never, ever rely on floating point arithmetic for iteration/indexing variables. They may run you into strange situations, and even worse, different processors handle floating points differently. Your example doesn't seem to have any side-effects of floating points, but using floating points is really a bad practice.

Categories