I have the following JS code
$(document).ready(function(){
update_items();
adjust_size_of_menu();
});
var adjust_size_of_menu = function() {
// global boolean set in update_items_count();
if ( !items_updated )
{
alert("Treatment of update_items() not done yet");
setTimeOut( function(){ adjust_size_of_menu(); }, 1000);
}
// More treatment goes here
}
As you can see, I am setting a variable in the first function. This variable must be true before I proceed with the execution of the rest of the instructions in the second function.
The problem here is that the first time I go into adjust_size_of_menu(), it shows me the alert, which is fine. After that, it should wait 1 second then re-execute the adjust_size_of_menu() from the beginning until the item_updated boolean is true, then we continue with the rest of the code.
What is the problem with this code? I've already used the same approach elsewhere and worked just fine.
setTimeOut is not a built-in function in javascript. If you've used it elsewhere, it's because you or someone else declared it. The correct spelling is setTimeout. Note the lowercase "o".
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
javascript is case sensitive language and it should be setTimeout()
Related
I'm trying to get a javascript function to run only once. I've seen this question has been asked before, e.g. Function in javascript that can be called only once, but I can't get the solutions in here to work. I'm not sure if it's because I've got nested functions, or whether there's something I'm missing. Essentially, I'm trying to run a function which, when a webpage is scrolled, it:
- runs a little animation on a canvas in the header
- reduces the size of the header
- leaves it at that
But when there is any subsequent scrolling, the animation keeps re-running. Here's a summarised version of the non-working code:
$(document).on("scroll",function(){
var arrange_title = function(){
//some code
};
if($(document).scrollTop()>0){
arrange_title();
arrange_title = function(){};
setTimeout(function(){
$("header").removeClass("large").addClass("small");
},1000);
}
});
I've also tried declaring a global variable, setting it to "false" in a "window.onload" function, then set it to true in an if function that runs the animation (the if function running only if the variable is false), but that doesn't stop it either. Thoughts?
What you're looking for is something along the lines of listenToOnce where the listener fires the one time, but never again. This could be modified to a number of calls, but the logic is like so:
Register the listener.
Then once the listener fires, remove it.
See .off
$(document).on("scroll",function(){
var arrange_title = function(){
//some code
};
if($(document).scrollTop()>0){
arrange_title();
arrange_title = function(){};
setTimeout(function(){
$("header").removeClass("large").addClass("small");
// $(document).off('scroll'); // or here
},1000);
}
$(document).off('scroll'); // remove listener, you can place this in the setTimeout if you wish to make sure that the classes are added/removed
});
Don't use a time out. That is why you are getting in trouble. Declare a variable outside of your function using var, that will make it global. Your code should be inside of a check for that variable. Before executing your code the first time but inside of the check, change that variable so that the code will never run again.
Try avoid setTimeout. Almost all animation can be watched for end.
function doHeaderAnimation() {
return $('header').animate();
}
function makeHeaderSmall() {
$("header").removeClass("large").addClass("small");
}
function handleScroll(event) {
if ($(document).scrollTop() > 0) {
doHeaderAnimation().then(makeHeaderSmall);
$(document).off("scroll", handleScroll);
}
}
$(document).on("scroll", handleScroll);
I have a short piece of code that I meant to implement into a page;
$(document).ready(function() {
$("h1").hide();
$("h2").hide();
$("h3").hide();
});
$(function() {
$("h1").delay(2000).show().animate({
marginTop: "40%"
}, 1000);
return;
});
Well, I guess after glancing again I have two questions.
First question: should the 'return' statement be used at the end of every
function to indicate the function is complete?
Second Question:
And if it is complete, and the layout of page has been manipulated by the function shouldn't the styling and anything else that was changed return to it's original state? mine did not. and actually stopped everything from proceeding after this function. with or without the 'return' statement.
I want to set delay in javascript code so that XML file generated before running of javascript . Here is my html code
<body onLoad="Func1Delay()">
<div id="map"></div>
</body>
In this Func1Delay() function i have written code to delay execution of javascript
function Func1Delay()
{
setTimeout("load()", 3000);
}
load() is javascript function ? how can i delay execution of javascript code so that xml file successfully generated before code execution??
Seems like your downloadUrl function provides a callback. The callback function fires automatically, after the XML is loaded. You do not need a 3 second delay, just move your logic inside the callback function. Something like this:
function Func1Delay() {
downloadUrl("location.xml", function (data) {
var xml = data.responseXML;
// do any thing with xml, it is loaded!
// alert(xml);
});
}
That's how you do it, except you don't want to use a string (although it works — provided you have a function called load defined at global scope). setTimeout schedules a function to be called a given number of milliseconds later.
It's better to give it an actual function reference:
function Func1Delay() {
setTimeout(load, 3000);
function load() {
// Stuff to do three seconds later
}
}
Note that the event you're using to trigger it, the onload of body, already happens really, really late in the page load cycle, and so whatever you're waiting for may already be done; conversely, if it might take more than three seconds, you might not be waiting long enough. So if there's something you can check to see whether it's done or not, you can poll, like this:
function Func1Delay() {
check();
function check() {
if (theWorkIsDone) {
// Do something with the work
}
else {
// Check back in 100ms (1/10th of a second)
setTimeout(check, 100);
}
}
}
You want the function to execute as soon as possible, but in every case after your xml has been successfully generated.
In this case you should prevent using a fixed amount of time (because you don't know the value exactly), but try the following:
function load(){
if (/*check here if the xml has *not yet* been generated*/){
setTimeout(load,50); // try again in 50 milliseconds
return;
}
// do your stuff here
}
This loops as long as your xml is not ready, and kicks in as soon as it's available.
General about setTimeout:
You can pass a string, but this is highly discouraged from for several reasons.
Instead pass a function reference or a function like this:
// function reference
setTimeout(load,3000) // no `()` !
// function
setTimeout( function(){load()},3000)
If you need paramters be passed to the function, you can't use the first option but need to use the second one, where you can easily pass them load(params).
If you pass a function like this: setTimeout(load(),3000) it executes the function load and passes its return value to the timeout. You however want the function invoked after 3 seconds and thus only pass the reference to the function.
Notice however, that you have a different scope if you execute the functions this way.
I basically want to know how global variables work in a javascript/JQuery environment. I am most familiar with a language called processing which I've been told is java-based. I expected variables in javascript and JQuery to behave like the ones in processing, but they do NOT work as I expect and I cannot for the life of me wrap my head around it.
I have a very simple example made up to illustrate my confusion:
var what="";
$(document).ready(function(){
$("p").click(function () {
what="p";
});
if(what=="p"){
alert(what);
}//end if
});//end doc ready
In processing, this would work because the 'what' variable is global and as it is changed by clicking on a paragraph, the if statement should be continuously checking to see if 'what'=='p', and trigger the alert. But that is not what happens-- 'what' only seems to be updated WITHIN the click function, even though it is a global variable, so when it comes to the if statement, 'what' still equals "" instead of "p".
If someone could explain why this happens, I will be very grateful!
The if statement only runs once when the DOM is first ready. It is not running continuously. If you want it to run during the click handler, then you would use this code:
var what="";
$(document).ready(function(){
$("p").click(function () {
what="p";
if(what=="p"){
alert(what);
}//end if
});
});//end doc ready
the if statement should be continuously checking to see if 'what'=='p', and trigger the alert.
Why? None of your code produces that functionality. If you want that to happen, you can use setInterval():
setInterval(function() {
if(what=="p") {
alert("what");
}
}, 500); // executes function every 500 milliseconds
But that is not what happens-- 'what' only seems to be updated WITHIN the click function, even though it is a global variable
No, your what variable is being updated globally. You just don't notice because you made false assumptions about the if functionality (it's only being called once).
I am having difficulties testing window.setInterval function in my Javascript file. Below is the scenario... basically I have a setInterval function in a function which I want to test:
var dummy = false; // global variable not set anywhere else
var INTERVAL_TIME = 20; // global variable not set anywhere else
function myFunction()
{
var id = window.setInterval(function() {
if (...)
{
window.clearInterval(id);
}
else
{
if(...)
{
dummy = true;
}
}
}, INTERVAL_TIME);
}
And I have the following test code in JsTestDriver:
TestMyFunction.prototype.test_myFunction() {
myFunction();
assertTrue(dummy);
}
Everytime the test executes, it fails and says dummy is false, as if the entire setInterval function was never called. I tried playing around with the interval with no success. If I put in an alert in the else clause, it popped up in a fraction of a second and disappeared (and test still fails).
The code works. I have a feeling that it is a timing issue, where the test finishes earlier than the setInterval function, hence complaining that dummy is not set to true. Any suggestions/solutions to this problem?
Thanks.
Why not put a setTimeout in your test, to delay checking for the value of dummy until after 25ms.
I used the JsUnitMockTimeout.js to simulate the setInterval function. It worked like a gem :)
assertTrue(dummy); is executed before the timeInterval of 20ms. Since you are using interval, do you perdiodically poll for the dummy value? First time poll is going to give you false unless you have a super slow PC.
It appears that "JsTestDriver cannot perform asynchronous testing". The only JS Unit testing frame work I have used with async support is Qunit.
Qunit has asyncTest which will work with ajax or timeouts.
PS: there a brand new JS Testing framework Evidence. I have not tried it.