setTimeout working fast - javascript

var k=0;var n=0;
function shiftrigh(){
n=n+1;
if(n<=193)
window.setTimeout(shiftright(),100);
else
n=0;}
function shiftright(){
k-=1;
document.getElementById("abcmngcontainer").style.left=k+"px";
window.setTimeout(shiftrigh(),100);
}
function shiftlef(){
n=n+1;
if(n<=193)
window.setTimeout(shiftleft(),100);
else
n=0;}
function shiftleft(){
k+=1;
document.getElementById("abcmngcontainer").style.left=k+"px";
window.setTimeout(shiftlef(),100);
}
Hi, I have the above code. The function shiftrigh when called invokes shiftright and then a cycle
is created then goes on until n is 193. Same is the case for the shiflef pair.
The code is working but it is working pretty quick. Whether I decrease the time value in settimeout or increase it, it remains the same. The updates are pretty quick, not smooth enough to see.

Change:
window.setTimeout(shiftright(),100);
to:
window.setTimeout(shiftright,100);
Note the missing parens. The same with shiftleft() -> shiftleft.
This is a common misunderstanding in JavaScript. setTimeout() requires a reference to a function (shiftright). What you are doing is calling that function immediately and passing whatever was returned from it to setTimeout(). Clearly not what was intended.

You are using window.setTimeout wrong!
window.setTimeout(shiftlef(),100);
You have to pass a function reference, not the return code of the function.
So the right version looks like this:
window.setTimeout(shiftlef,100);

setTimeout will need a function-NAME or a function-"variable"/"pointer" as first argument...
in your code, you pass the RETURN value of your function-call as first parameter to "setTimeout"....
just remove the braces ->
window.setTimeout(shiftleft, 100)

Related

javascript How to make an odometer to start counting onload?

How to make an odometer to start counting onload https://jsfiddle.net/aht87opr/6/ ? (I've tried but to no avail, the snipet which should start it is at the bottom of javascript). I am javascript beginner please help :)
This is Gavin Brock's Odometer http://brock-family.org/gavin/software/web/odometer.html
//<![CDATA[
var n = 0;
var myOdometer;
function startcounting () {
var div = document.getElementById("odometerDiv");
myOdometer = new Odometer(div, {value: n, digits: 6, tenths: true});
update();
}
function update () {
n=n+0.0025
myOdometer.set(n);
setTimeout("update()", 0);
}
//]]>
startcounting();
it does not work because setTimeout wants you to pass a function handle (you pass a string)
try setTimeout(update, 0);
From MDN:
A string passed to setTimeout is evaluated in the global context, so local symbols in the context where setTimeout() was called will not be available when the string is evaluated as code.
Additionally,
This syntax is not recommended for the same reasons that make using eval() a security risk.
Your code isn't working because setTimeout, when passed code as a string, can't see your update method. You can both fix this and improve the quality of your code by just passing update directly, as #dolek recommends

can't change the a variable value in the javascript function

I am new to Javascript, I am confused about the code below for hours.
I wanna know why i can't assign the value of result to htmlContent.
Thanks!
var htmlContent = fs.readFileSync(program.file);
restler.get('http://google.com').on('complete', function(result) {
if (result instanceof Error) {
util.puts('Error: ' + result.message);
} else {
htmlContent = result;
}
});
console.log(htmlContent);
The problem here is that the line starting with restler.get begins before the console.log, but it doesn't finish before it necessarily.
You should put your console.log inside the restler.get call.
I would look up the concept of futures and promises in JS, this might help clear up some fundamentals:
http://monochrome.sutic.nu/2012/04/06/javascript-futures.html
When you are using continuations in JS (a requirement in node.js especially), you really need to get your head around them.
Here, your function inside the .on() will be called asynchronously (in simple words it will get executed when "complete" event occurs i.e. some later time) and you are using console.log(htmlContent) is regular function call, so you can not set htmlContent value inside the function this way.
If you want to use result value in any other function then you should pass this value to your next function. I hope this will work.

slideshow counter disappears

I have this code that is supposed to generate a counter for a slideshow and then change the picture and the corresponding number color in the counter. However, after the slideshow cycles through twice, the counter changes to display:none and then reappears and disappears every time the slideshow begins its cycle.
//icons for newsreel guide
for(i=0;i<document.getElementsByClassName("news").length;i++){
var count=i+1;
$('#counter').append('<span class="count">'+count+'</span>');
}
//newsreel script
$(".news").hide();
setTimeout (function() {
var wait = $(".news:last").index()*12000+12000;
function newsreel(){
var i=0;
(function showNews(elem){
if(i==document.getElementsByClassName("count").length){
i=0;
}
document.getElementsByClassName("count")[i].style.color="#000";
elem.fadeIn(2000,function(){
elem.delay(8000).fadeOut(2000,function(){
document.getElementsByClassName("count")[i].style.color="#3159a0";
i=i+1;
$(this).next().length && showNews($(this).next());
});
});
})
( $(".news:first"));
setTimeout (arguments.callee, wait);
}/*end newsreel()*/
newsreel();
}, 2000);
At first I thought it was using the deprecated arguments.callee but I changed that and it still happens on cue. Any ideas?
I checked your code, and the problem is in this line :
$(this).next().length && showNews($(this).next())
.next() is getting the next sibling. Your counter is a sibling of .news. To solve your problem, do this:
$(this).next().length && showNews($(this).next('.news'))
That will select the next sibling with the class news.
I suspect it's because your showNews function is never running. I think the JavaScript engine is evaluating
(function showNews(elem){
//...
})
and
( $(".news:first"));
as two different expressions, rather than passing $(".news:first") as a parameter to showNews as you intend. Since ; at the end of a line is optional in JS, the parser will insert one automatically if the result is valid JavaScript. In this case, it defines a function but never calls it, then builds a jQuery sequence but never uses it.
Try removing the carriage return between the two:
(function showNews(elem){
//...
})($(".news:first"));

Why is my array separating itself out in Javascript?

So I'm trying to make this smooth color fade transition for my website. I made a function that should do just that, and it even looks like it would work, but I am having a problem I do not understand in the least, nor have I even seen anything like it before. I am using recursion in my function and passing a color I changed back into the function to be changed again. I only exit when the current color matches the target color. What I have COMPLETELY CONFIRMED is happening is that when I pass the 2 arrays back into the function again, they split themselves apart.
Ex: before being passed through, startColsAr=[211, 211, 211].
after being passed through, startColsAr=['2'; '1'; '1'; ','; '2'; '1'; '1'; ','; '2'; '1'; '1'].(semi-colons were used to make reading easier).
As you can see in my function below, nowhere am I doing anything to change the contents of the arrays like that.
Here is my function:
function transitionOut(startColAr,endColAr, waitTime, interval, page){
//change the colors
for(var i=0;i<3;i++){
if(startColAr[i]<endColAr[i]){
startColAr[i]+=interval;
if(startColAr[i]>endColAr[i]){startColAr[i]=endColAr[i];}
}else if(startColAr[i]>endColAr[i]){
startColAr[i]-=interval;
if(startColAr[i]<endColAr[i]){startColAr[i]=endColAr[i];}
}
}
//var color="rgb("+startColAr[0]+", "+startColAr[1]+", "+startColAr[2]+")";
var color = "#"+startColAr[0].toString(16)+startColAr[1].toString(16)+startColAr[2].toString(16);
document.body.style.backgroundColor = color;
if(startColAr[0]==endColAr[0] && startColAr[1]==endColAr[1] && startColAr[2]==endColAr[2]){
location.href=page;
}
window.setTimeout("transitionOut(\'"+startColAr+"\', \'"+endColAr+"\', \'"+delay+"\', \'"+interval+"\', \'"+page+"\')",waitTime);
}
Now, I am only passing in 3 values for both arrays, so I could easily change the 2 arrays to 6 integer parameters(and probably get the function to work(so don't tell me to go download a new library for transitions, THIS IS ABOUT ARRAYS)), but I want to know why this is happening. Does anyone have any suggestions? I have tried a bunch of different things to narrow it down, but I can't seem to put a dent in this at all. A little help?
The problem is with the line:
window.setTimeout("transitionOut(\'"+startColAr+"\', \'"+endColAr+"\', \'"+delay+"\', \'"+interval+"\', \'"+page+"\')",waitTime);
You are converting your arrays into strings when you are preparing the code to be run later. As per the Mozilla doc, it would probably be easier to use the alternate form of the setTimeout function:
window.setTimeout(transitionOut, waitTime, startColAr, endColAr, waitTime, interval, page);
I think this line is your problem
window.setTimeout("transitionOut(\'"+startColAr+"\', \'"+endColAr+"\', \'"+delay+"\', \'"+interval+"\', \'"+page+"\')",waitTime);
You probably want something like
window.setTimeout(transitionOut, waitTime, startColAr, endColAr, waitTime, interval,page,waitTime);
You can call setTimeout with a string literal but I don't think it's recommended.

Why is setInterval calling a function with random arguments?

So, I am seeing a curious problem. If I have a function
// counter wraps around to beginning eventually, omitted for clarity.
var counter;
cycleCharts(chartId) {
// chartId should be undefined when called from setInterval
console.log('chartId: ' + chartId);
if(typeof chartId == 'undefined' || chartId < 0) {
next = counter++;
}
else {
next = chartId;
}
// ... do stuff to display the next chart
}
This function can be called explicitly by user action, in which case chartId is passed in as an argument, and the selected chart is shown; or it can be in autoplay mode, in which case it's called by a setInterval which is initialized by the following:
var cycleId = setInterval(cycleCharts, 10000);
The odd thing is, I'm actually seeing the cycleCharts() get a chartId argument even when it's called from setInterval! The setInterval doesn't even have any parameters to pass along to the cycleCharts function, so I'm very baffled as to why chartId is not undefined when cycleCharts is called from the setInterval.
setInterval is feeding cycleCharts actual timing data ( so one can work out the actual time it ran and use to produce a less stilted response, mostly practical in animation )
you want
var cycleId = setInterval(function(){ cycleCharts(); }, 10000);
( this behavior may not be standardized, so don't rely on it too heavily )
It tells you how many milliseconds late the callback is called.
var cycleId = setInterval(cycleCharts, 10000, 4242);
From the third parameter and onwards - they get passed into the function so in my example you send 4242 as the chartId. I know it might not be the answer to the question you posed, but it might the the solution to your problem? I think the value it gets is just random from whatever lies on the stack at the time of passing/calling the method.

Categories

Resources