delaying a method of an object with jquery - javascript

I'm a jquery novice trying to write my first app here and one thing I've been trying to figure out is how to use the .delay() method if what I want to delay is the method of an object.
So for example, I have something like this:
dice = new Dice("#die1", "#die2");
dice.roll();
But I want there to be a delay before the roll() function is actually invoked. How would I do that?
I figured using jquery would be easier than pure javascript because I know that using setTimout() is tricky to use with your own methods.

There is nothing tricky or dangerous about setTimeout and it's likely the most appropriate approach here. It's specifically designed to execute functions after a given time has expired.
For example here's a 1 second delay
dice = new Dice("#die1", "#die2");
setTimeout(function() { dice.roll(); }, 1000);

Related

Create a unique function name on the fly for shared timer

I'll start with the exact nature of the problem and then give some background. I am trying to name a function -threadTimer- and give it a random unique identifier, such as 'threadTimer'+ID. A randomly generated ID would work fine. Then, I need to use setInterval on it, to make it fire repeatedly and therein lies my coding problem. I have tried every variation of new, function, function as an object and I just can't get my head around it. You'll notice that the function I have created is an object and perhaps this is where I'm going in circles.
OK, the background I mentioned. threadTimer is fired by a master timer co-ordinating several threads. That's why you'll see I have generated a 'global' object for reference elsewhere. similar HTML entities can fire threadTimer at the same time, hence my requirement to make each instance unique.
window['GlblThreadExe'+ID]=setInterval(function(){threadTimer(elid,parent,lft,top,diameter,point,bStyle,color,grp,startTime,size,ID,counter,div,divwth,divht,wthIncrement,htIncrement,lftStart,topStart,lftIncrement,topIncrement)},interval);
function threadTimer(elid,parent,lft,top,diameter,point,bStyle,color,grp,startTime,size,ID,counter,div,divwth,divht,wthIncrement,htIncrement,lftStart,topStart,lftIncrement,topIncrement){
// more code
}
In truth, I think its the volume of parameters that I'm passing that's confusing my syntax. Any help appreciated
Avoid polluting window
Generally instead of polluting the global namespace you can store your setInterval ids in some variable
let intervalIds = {}
intervalIds['GlblThreadExe'+ID] = setInterval(function()...)
If really necessary, then store intervalIds to window
window.intervalIds = intervalIds;
Wrap your anonymous function
When you create the "clock", do not call setInterval directly:
Here, createTimerWithId will return a function which calls threadTimer
Dirty id generation
Use a timestamp, and mix it with some random stuff. Or better use a UUID
setInterval(createTimerWithId(), 1000)
function createTimerWithId(){
let id = Date.now()+Math.random(); //no lib, oneliner. good enough to debug
return function(){//the same function you gave to setInterval in your example
threadTimer(id, ...)
}
}
We can do better
In 1. we generated an id on the fly and thus
your code is not testable (id will always change(well except if you mock Math and Date...)).
your id is ugly (a float...)
it will be hard to know from which setInterval you come from
instead, give it the ID.
function createTimerWithId(ID){
return function(){//the same function you gave to setInterval in your example
threadTimer(ID, ...)
}
}
window['..'+ID] = setInterval(createTimerWithId(ID));
shorter version being
window['..'+ID] = setInterval((id=>{
return function(){
threadTimer(id, ...)
}
})(ID),1000);

In JavaScript, is there a universal approach to known when asynchronous actions are finished?

In my work, I frequently encounter following situation:
Situation A:
I need to make multiple ajax calls in one function to retrieve data from server. So I have to make callback functions and define a counter to determine whether all the calls get done.
For example , in each of the sub-functions ( with ajax calls), at the end of the done, I would callback to check the counter's value.
ajax.done(funciton(jsResponse){
.......
base.ajaxLoaded++;
base.dataLoaded();
});
then in base function, I check the value:
dataLoaded: function()
{
var _this = this;
if (_this.ajaxLoaded == 4)
{
// all loaded
_self.render();
_this.afterInit();
}
}
Situation B:
There is a modal pop up triggered by the completion of an animation. So, I have following choices:
1) make a setTimeout function with a timer ( estimated the length of animation)
something like:
setTimeout(function(){
window.MYAPP.triggerMymodal();
},1000);
2) set up a interval function to check repeatedly whether a flag's value has changed and I embedded this flag into the animation finish function, to set it true or false.
if this flag true then make my next move and kills this interval.
3) change animation div attributes and check it use interval function.
Situation C:
Use window.print() function to print something and then need detect when it's finish. This has been asked by myself in this:
how to detect window.print() finish
My Question:
In JavaScript, is there a certain kind of method or Technic to deal with those functions which have unknown execution time? or this is just a case by case thing based on what technology you use?
Yes, the modern approach to dealing with this is called Promises. Various libraries implement the concept, which is basically that you can chain together groups of things that need to happen, either is parallel or serial, and then define success and failure outcomes for each of them.
It takes a bit of time to get your head around it but once you do the code is much more straightforward.

How to halt Javascript code without alert

Is, is there any function which does the exact same thing as alert except doesn't bring up an alert box? (a function which halts ALL executing JS code for a given amount of time, but doesn't bring up an alert message).
setTimeout doesn't work since it only halts the cod which is inside the setTimeout function.
a javascript function that will stop your code for some time is setTimeout(),
for more information on how to use this function please reffer to the following link : http://www.w3schools.com/jsref/met_win_settimeout.asp
You could split it into two functions and have the first initiate a time-out.
function func1(){
//do stuff
setTimeout('func2',2000);
}
function func2(){
//do some more
}
The function setTimeout will execute for later whatever function you pass to it. So it will not really pause the execution of your code, unless the code is split into parts and placed within calls of setTimeout. Maybe that is an approach.
Another approach could be to use delay function (http://api.jquery.com/delay/) along your jquery calls.
But in all cases the best is to find out what is causing this behaviour and fix it in code.
Have you tried using the DOM elements rather than JQuery to create the new node.
http://www.w3schools.com/jsref/met_node_appendchild.asp
var startTime = new Date().getTime();
while(new Date().getTime() < startTime + 1000) {}
This waits for 1000ms / 1 sec.
During that time, your browser is completely unresponsive and possibly doesn't render any stuff you may be waiting for, but hey, ... there you go ;)

Sleep function in Javascript

I'm new to JavaScript from Java, and I'm trying to implement a sleep(millis) function. Basically I need to make a request to an endpoint, and if it returns an error, wait a while and make the request again...
I've found JavaScript's setTimeout() function, but it has a strange (for me) behaviour, because it seems that the code is still running, and I don't want to do anything but wait...
After a little research I've found this function here:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
With this function I achieve exactly what I want, but I understand it may not be the proper way to do it and I didn't find any other solutions like this... So, I'd like to know, in your opinion, is this:
A perfectly valid solution?
A not too bad workaround?
Just painful to your eyes?
Well, opinions will vary. I can understand you though, JavaScript doesn't have a real sleep function like Java or any other language (like Perl, Bash, PHP, etc)
http://devcheater.com/ shows multiple variations, but also check out these Stackoverflow topics:
What is the JavaScript version of sleep()?
What's the best way to implement a sleep function JavaScript?
How to make a REAL sleep() in JavaScript?
You say you don't like setTimeout, but basically, that's what you need to do.
function myFunc() {
// Do the work
setTimeout(myFunc, sleepInterval);
}
(Assuming you're trying to create a repeating schedule, if not, call your other function rather than myFunc again).
You can (and probably should) of course add some termination logic as well.
Then start your work with myFunc(). You could also use setInterval, but it can cause some problems if your intervals start to overlap.
Regarding your solution, I select option 3...
There is no sleep function in Javascript, and you should consider using window.setTimeout to call the next operation. I certainly would not burn cycles in a for loop. But if you must wrap it in a function named sleep then here is an example to give you an idea.
function sleep(callBack, milliSecs) {
setTimeout(callBack, milliSecs);
}
function first() {
console.log("first");
}
function second() {
console.log("second");
}
first();
sleep(second, 5000);
On jsfiddle
The problem in this code is that is stays busy all the time until the code finishes. This may cause a warning dialog in many browsers, and it also slows the page down.
Here I would still prefer to use the setTimeout function. The syntax is quite simple:
setTimeout("codeToBeExecuted()", milliseconds);
You can simplify it by saving the code after sleeping in a function, and passing the needed data in global variables or like this:
setTimeout('whenDone(' + numericData + ', "' + stringData + '")', milliseconds);
JSFiddle

window.setInterval - is it possible to have more than one? how?

I have created a slideshow widget, using jQuery.UI widgets that works with window.setInterval.
I am trying to have more than one slideshow in the same page and i get the following results:
If I try invoking the same widget for both of my divs with images:
$('#div1').slideshow();
$('#div2').slideshow();
none of them work;
I have cloned the definition of my widget and named it slideshowsmall
$('#div1').slideshow();
$('#div2').slideshowsmall();
and only the second one works.
my widget code is in this pastebin, but i really think the problem, at least in the second try, has to do with setInterval
Thanks
Having multiple setInterval() by itself cannot be causing problems. It is more likely to have something to do with the code it's executing (and your widget code being non-english makes it very hard to analize and comprehend).
setInterval() returns and integer ID of the "interval", so that you can later clearInterval(...) by passing this ID. This scenario was implemented exactly for multi-interval uses. More details on MDC
As per your widget code when setInterval calls the ChangeLeft/Right.. method the slideshowdiv variable always points to the last element on which slideShow is called. the reason for this is the way you are invoking change methods which is not adviceable.
Please use the below code to call your change method it should solve your problem. You will notice I am passing the slideshowdiv object to change methods.
this.options.timer = window.setInterval(function () {
ChangeImageLeft(velocidade, slideshowdiv);
}, intervalo);
Let me know if you need more info.

Categories

Resources