setTimeout() multiple JQuery instances - javascript

So I have a block of about 10 lines of code in JQuery. the lines are all independent, and when I execute them (I just type them in the console, its an automated test) i need them to be delayed form each other, like with 2 seconds difference. I started by using JavaScript setTimeout() on each line, but for 10 separate lines of code i assume there's a sexier way to do so... Also JQuery DELAY doesn't work since these aren't effects. Any ideas? here's the general idea of my code block..
$("#tag1").trigger("click");
$('#tag2').val("some text");
$("#tag3").trigger("keyup");
$('#tag4 select option[value="4"]').prop('selected',true);
$("#tag5").val(6);
$('#tag6').val(3).change();
$('#tag7').val(30).change();
$('#tag8').val("2017-06-29");
$('#tag9').val("2015-06-29");
$('#tag10').val("This is the test tasks' description.");
$(".id1").trigger("click");
$(".id2").val("buy oranges");
As you can see all the tags and ID are unique...
any idea would be greatly appreciated!

From my comment: An array of anonymous functions would be one option. Pass them recursively to a function that uses setTimeout Slicing off the first one each time..
e.g. something like this (the test just prints the functions to console as the DOM elements are missing):
JSFiddle: http://jsfiddle.net/bnq6tppb/1/
var operations = [
function () {
$("#tag1").trigger("click");
},
function () {
$('#tag2').val("some text");
},
function () {
$("#tag3").trigger("keyup");
},
function () {
$('#tag4 select option[value="4"]').prop('selected', true);
},
function () {
$("#tag5").val(6);
},
function () {
$('#tag6').val(3).change();
},
function () {
$('#tag7').val(30).change();
},
function () {
$('#tag8').val("2017-06-29");
},
function () {
$('#tag9').val("2015-06-29");
},
function () {
$('#tag10').val("This is the test tasks' description.");
},
function () {
$(".id1").trigger("click");
},
function () {
$(".id2").val("buy oranges");
}];
and use recursively with a timer:
function processoperations(ops){
// Run the first operation
ops[0]();
setTimeout(function(){
if (ops.length > 1){
// Go recursive after 2 seconds
processoperations(ops.slice(1));
}
}, 2000);
}
and start like this:
processoperations(operations);
This allows you to process any code at intervals. The alternative (as others mentioned) is an automated testing tool (like Selenium) if this is actually a testing problem. Update: You have mentioned you are not allowed to use Selenium.

Related

Unexpected behavior with "SetInterval" in JavaScript

I have a JavaScript that makes request to a servlet. The request works but I can't get it to repeat at the specified time interval of 1 sec. What am I doing wrong?
I am quite new to front-end development and JavaScript.
$(document).ready(function() {
$('#userName').blur(function(event) {
var name = $('#userName').val();
setInterval($.get('JqueryServlet', {
userName : name
}, function(responseText) {
$('#ajaxResponse').text(responseText);}), 1000);
});
});
setInterval works with the arguments setInterval(callbackFunction, timingInMilliseconds).
It looks like you are putting your call to $.get directly in the callbackFunction argument. This unfortunately doesn't work as the result of your call to $.get is passed as the argument, not the function itself. Even if you did pass the function, it wouldn't be called with the proper arguments.
Instead wrap it in an anonymous function call or place it in a function, like so:
function getServlet() {
// code
}
setInterval(getServlet, 1000); // to go off every 1 second
Or:
setInterval(function() {
// code
}, 1000);
If you insisted on using $.get directly in setInterval, you could use something like:
setInterval(function(a,b,c){
console.log(a + b +c);
}, 500, "a", "b", "c");
In most browsers (see the link above) you can use setInterval with the call:
setInteval(callbackFunction, timingInMilliSeconds, callbackArg, callbackArg, ...);
Anything you want to do, put inside of this block below:
setInterval(function(){
alert("I will be called in 3 second and again after 3 seconds");
}, 3000);
Try it now with this:
$(document).ready(function() {
$('#userName').blur(function(event) {
var name = $('#userName').val();
setInterval(function(){
$.get('JqueryServlet', {
userName : name
}, function(responseText) {
$('#ajaxResponse').text(responseText);
});
}, 1000);
});
});
on any blur event you create new instance of interval and they remain in memory and can cause conflict ,create a global interval ref object and set interval reference to it and before start new interval dispose old interval.

How to test code inside $(window).on("load", function() {}); in Jasmine

I have a javascript below, which appends a DIV on page load and hides it after 3 sec.
var testObj = {
initialize: function() {
var that = this;
$(window).on("load", function() {
(function ($) { //Append Div
$('body').append("<div>TEST</div>");
})(jQuery);
that.hideAppendedDiv();
});
},
hideAppendedDiv: function() { //Hide appended Div after 3s
setTimeout(function(){
$("div").hide();
}, 3000);
}
};
//call Initialize method
testObj.initialize();
How to write Jasmine test cases for the methods in the code.
I'm guessing that you don't really want to test a Javascript function such as $(window).on('load')... , but that your own function hideAppendedDiv() get's called from $(window).on('load'). Furthermore, you want to make sure that the function hideAppendedDiv() works as well.
IMO, you need two expects.
Somewhere in your setup beforeEach function:
beforeEach(function () {
spyOn(testObj , 'hideAppendedDiv').and.callThrough();
});
Expectations
it('expects hideAppendedDiv() to have been called', function () {
// make the call to the initialize function
testObj.initialize ();
// Check internal function
expect(testObj.hideAppendedDiv).toHaveBeenCalled();
});
it('expects hideAppendedDiv() to hide div', function () {
// make the call to the hideAppendedDiv function
testObj.hideAppendedDiv();
// Check behavior
expect(... check the div ...)
});
Edit
Just to be clear, Jasmine executes all the expects in order. Now, if you have two functions fn_1(), and fn_2() and you want to test that they were called in order you can setup yet another spi function that returns a specific value, or a sequential and incremental set of values every time it is called.
beforeEach(function () {
spyOn(testObj , 'fn_1').and.returnValues(1, 2, 3);
spyOn(testObj , 'fn_2').and.returnValues(4, 5, 6);
});
The first time fn_1 is called it will return 1, respectively fn_2 will return 4.
That is just one of the ways, but you have to get creative when testing.
Now if you want to test that a function was called after x amount of time here is a post that already explains it.
You don't need to test the window load event, if you move the append code out of the anonymous function call and pass it into the event handler instead you can test the functionality in exactly the same way you would anything else and your code will be better structured.

Pause execution in while loop locks browser (updated with fiddles)

I know my problem I just not sure how to resolve it. I have a custom domain and in a function call a while loop executes. In that loop i wanted an animation to occur in order.
So the first problem is that javascript by its nature executes every line thus item 2 starts before item 1 completes. Now the effect is so short that it "appears" to happen to all elements at once but in the debugger it is just looping one at a time.
Now my typical resolution would be to use SetTimeout() but that is causing the browser to lock. Reading this post (Trying to delay/pause/slow a while loop in jQuery) it makes sense that the browser is getting into an endless loop.
So how can I get a pause between element1 and element2 events? I thought perhaps to add a callback function to my custom domain but not sure if that will work as desired besides not being sure how to do it.
In the head of the page and read the comments for anything else I may be doing wrong or could do better.
$(document).ready(function ()
{
//pause long enough for person to visually take in page before starting
setTimeout(function () { PageLoadAnimation.onReady(); }, 1000);
});
My custom domain:
var PageLoadAnimation =
{
onReady: function ()
{
//black everything out just to be sure
PageLoadAnimation.BlackOutElements();
//flash & show
PageLoadAnimation.FlashElement();
},
BlackOutElements: function ()
{
$('#ParentContainer').children().hide();
},
FlashElement: function ()
{
//get array of all elements and loop till all are visible
var elementArray = $('#ParentContainer').children();
var $els = $('#PartialsContainer').children();
while (elementArray.length)
{
var $el = elementArray.eq(Math.floor(Math.random() * elementArray.length));
//if I put set timeout here is causes the infinite loop
PageLoadAnimation.FlashBlast($el);
elementArray = elementArray.not($el);
//if I put by itself it no diff as the while loop continues regardless
//setTimeout(1500);
}
},
FlashBlast: function ($el)
{
//flash background
$el.fadeIn(200, function () { $el.fadeOut(200) });
}
}
I'm not sure if it isn't working or if I am doing something wrong so I created these fiddles:
Original Fiddle
With Johan Callbacks
Using is animating property
WARNING THIS ONE WILL HANG YOUR BROWSER!
I don't think I am checking the isAnimating property the way Johan had in mind??
ANSWER FOR THIS SITUATION. Hopefully it will help others.
setTimeout in a loop was really my problem...but not the only problem. I was the other problem(s).
Me first.
Fool that I am I was really causing my own complications with two things I was doing wrong.
First using jsfiddle my javascript would error due to syntax or some such thing but fiddle doesn't tell you that (to my knowledge) so my fiddle wouldn't run but I took it in pride as MY CODE IS FINE stupid javascript isn't working.
Second I was passing my function to setTimeout incorrectly. I was adding the function parens () and that is not correct either which would bring me back to issue one above.
WRONG: intervalTimer = setInterval(MyFunction(), 1500);
RIGHT: intervalTimer = setInterval(MyFunction, 1500);
As for the code I read here (http://javascript.info/tutorial/settimeout-setinterval) setting a timeout in a loop is bad. The loop will iterate rapidly and with the timeout one of the steps in the loop we get into a circular firing squad.
Here is my implementation:
I created a couple variables but didn't want them polluting the global scope so I created them within the custom domain. One to hold the array of elements the other the handle to the setInterval object.
var PageLoadAnimation =
{
elementArray: null,
intervalTimer: null,
....
}
In my onReady function (the one the page calls to kick things off) I set my domain array variable and set the interval saving the handle for use later. Note that the interval timer is how long I want between images flashes.
onReady: function ()
{
elementArray = $('#PartialsContainer').children();
//black everything out just to be sure
PageLoadAnimation.BlackOutElements();
//flash & show
intervalTimer = setInterval(PageLoadAnimation.FlashElement, 1500);
},
Now instead of looping through the array I am executing a function at certain intervals and just tracking how many elements are left in the array to be flashed. Once there are zero elements in the array I kill the interval execution.
FlashElement: function ()
{
if(elementArray.length > 0) //check how many elements left to be flashed
{
var $el = PageLoadAnimation.GrabElement(); //get random element
PageLoadAnimation.FlashBlast($el); //flash it
PageLoadAnimation.RemoveElement($el); //remove that element
}
else
{
//done clear timer
clearInterval(intervalTimer);
intervalTimer = null;
}
},
So the whole thing is:
var PageLoadAnimation =
{
elementArray: null,
intervalTimer: null,
onReady: function () {
elementArray = $('#PartialsContainer').children();
//black everything out just to be sure
PageLoadAnimation.BlackOutElements();
//flash & show
intervalTimer = setInterval(PageLoadAnimation.FlashElement, 1500);
//NOT this PageLoadAnimation.FlashElement()
},
BlackOutElements: function () {
$('#PartialsContainer').children().hide();
},
FlashElement: function ()
{
if(elementArray.length > 0)
{
var $el = PageLoadAnimation.GrabElement();
PageLoadAnimation.FlashBlast($el);
PageLoadAnimation.RemoveElement($el);
}
else
{
//done clear timer
clearInterval(intervalTimer);
intervalTimer = null;
}
},
GrabElement: function()
{
return elementArray.eq(Math.floor(Math.random() * elementArray.length));
},
RemoveElement: function($el)
{ elementArray = elementArray.not($el); },
FlashBlast: function ($el) {
//flash background
$el.fadeIn(100, function () { $el.fadeOut(100) });
}
}
Hope that help others understand the way to go about pausing execution in javascript.
A callback example that might help:
FlashBlast: function ($el, fadeInComplete, fadeOutComplete)
{
if(arguments.length === 3){
$el.fadeIn(200, function () {
fadeInComplete();
$el.fadeOut(200, fadeOutComplete);
});
}
}
Usage:
PageLoadAnimation.FlashBlast($el, function(){
//fadein complete
}, function(){
//fadeout complete
});
Another idea that might help:
isAnimating: false,
FlashBlast: function ($el)
{
var dfd = $.Deferred(),
that = this;
that.isAnimating = true;
$el.fadeIn(200, function () {
$el.fadeOut(200, function(){
dfd.resolve();
})
});
dfd.done(function(){
that.isAnimating = false;
});
}
Then make use of the private property isAnimating.
Finally, to know if an element is under an animation, you can use $el.is(':animated').
Hope this helps. Let me know if anything is unclear.

Can anyone explain why this JavaScript wont run

Im not very good wit JS and I just dont get why this wont work!
The code uses jquery to apply the pulsate efect to one of my divs and run forever unless I stop it with another function, but I cannot figure our why my first piece of code wont run!
function animate(var x){
// Do pulsate animation
$(x).effect("pulsate", { times:4 }, 5000);
// set timeout and recall after 10secs
setTimeout(animate, 10000);
}
$(document).ready(animate("#mydiv"));
Only way to get it working is for me to do this
function animate(){
// Do pulsate animation
$("#mydiv").effect("pulsate", { times:4 }, 5000);
// set timeout and recall after 10secs
setTimeout(animate, 10000);
}
$(document).ready(animate);
Note that in the first snippet the code uses variables to be more useful and the second piece has the selectors name hardcoded
Don't use var in your function declaration. Just use:
function animate(x){
Also, you probably want something like this for your first example:
function animate(x){
return function () {
function animateInner() {
$(x).effect("pulsate", { times:4 }, 5000);
setTimeout(animateInner, 10000);
}
animateInner();
};
}
$(document).ready(animate("#mydiv"));
DEMO: http://jsfiddle.net/XHKbC/
Otherwise, the original animate("#mydiv") call executes immediately (and $(x) probably won't find anything since the DOM isn't ready yet). $(document).ready() expects a reference to a function. You called a function instead. But that's all a little overkill. Just use:
$(document).ready(function () {
animate("#mydiv");
});
but you'll have to change your function so the setTimeout passes the value of x as well:
function animate(x){
// Do pulsate animation
$(x).effect("pulsate", { times:4 }, 5000);
// set timeout and recall after 10secs
setTimeout(function () {
animate(x);
}, 10000);
}
DEMO: http://jsfiddle.net/XHKbC/2/
Although it's a little more code/complex, my first example doesn't suffer the problem in my second (having to pass x in the setTimeout) by using a closure.
UPDATE:
Being shown how you are using this code, I'd set it up like this:
function Animater(target) {
var self = this;
var animateTO;
var animateElement = target;
function animate() {
animateElement.effect("pulsate", { times:4 }, 5000);
animateTO = setTimeout(animate, 10000);
}
self.start = function () {
animate();
};
self.stop = function () {
animateElement.finish();
clearTimeout(animateTO);
};
}
And create a new one like:
var mydivAnimater = new Animater($("#mydiv"));
You can then call .start() and .stop() on it, and you create any number of these Animater objects on different elements as you want.
DEMO: http://jsfiddle.net/K7bQC/3/
Your code has two issues:
omit the var:
function animate(x){
modify your event handler:
$(document).ready(function(){
animate("#mydiv");
});
You need to hand over a function reference (either animate or function(){}), not run the code right away which you are doing if you pass animate().
Now to not lose the reference to your x you have to modify the animate call in the timeout too:
setTimeout(function () {
animate(x);
}, 10000);
You dont need to type var when specifying a function parameter.

Delay Between Functions

this is my code snippet.
function customFadeIn () {
$("img.imgKit").each(function(index) {
$(this).delay(1000*index).fadeIn("slow");
});
console.log("one runs");
}
function customFadeOut () {
$("img.imgKit").each(function(index) {
$(this).delay(1000*index).not(document.getElementById('card-6')).fadeOut("slow" , function () {
$("#card-6").delay(1000).rotate({angle:0});
});
});
console.log("two runs");
}
I want the customFadeOut runs only after customFadeIn is done, therefore I call it by this
customFadeIn();
customFadeOut();
But it did not work, I think I did something wrong here, a help would be really helpful.
You can make usage of jQuerys Deferred / promise objects. Animations do also "inherit" those objects and you can apply jQuery.when() to shoot for multiple promises to finish.
There are several ways to re-structure your code for that, a simple implementation of this could look like:
(function() {
var promises = [ ];
function customFadeIn () {
$("img.imgKit").each(function(index) {
promises.push( $(this).delay(1000*index).fadeIn("slow").promise() );
});
}
function customFadeOut () {
jQuery.when.apply( null, promises ).done(function() {
$("img.imgKit").each(function(index) {
$(this).delay(1000*index).not(document.getElementById('card-6')).fadeOut("slow" , function () {
$("#card-6").delay(1000).rotate({angle:0});
});
});
console.log("two runs");
});
}
}());
If I did everything correct there, customFadeOut sets up a listener which waits for all animations / promises to finish, before it runs its own code. You don't even have to explicitly call the .promise() method at the end, jQuery applies some white magic to link that node with a promise internally for you.
Demo: http://jsfiddle.net/RGgr3/
Looks like I did everything correct ;)

Categories

Resources