Call function in itself in callback [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
i am not quite sure that Title related to my problem, so sorry.
I have asynchronous function that call callback function. So the main idea is I want to call function "dodo" each time after "asyncFunc" is done.
Are there some patterns for that? Are there issues releated to memory leak ?
var can = true;
function dodo() {
if(can)
{
can = false;
asyncFunc(function(data) {
doSmth();
can = true;
});
}
}
setInterval(dodo, 0);

The main idea is I want to call function "dodo" each time after "asyncFunc" is done.
So just call it there:
function dodoForever() {
asyncFunc(function(data) {
doSmth();
dodoForever(); // <==
});
}
dodoForever();
You don't need a global can state and setInterval.

You can just call it. Like so.
var can = true;
function dodo() {
if(can)
{
can = false;
asyncFunc(function(data) {
dodo(); // this will run `dodo` function again.
doSmth();
can = true;
});
}
}
setInterval(dodo, 0);
As the comments mention this will blow the stack up. You have dodo running every 0ms. This will basically call dodo a TON of times and that is basically all your program will be doing. I can't think of a use case where this would be necessary and it probably won't fair so well in terms of performance.
Really think about why you are trying to run it like that and what the end goal is.

Related

Is it possible to call local storage inside a function and use it in Windows.onload? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have a on click function which return 'x' and stores in div dynamically. After a page refresh, this dynamic div resets and the data is gone. But i want the data to stay. To do that i stored that in local storage and want to call later when page loads. I store it in local storage inside the function 'test'
and calling it in windows.onload which is returning null. I understand that i am unable to call the local storage inside the function. My question: Is there a way to call the local storage inside the function 'test'
function test(parameter1, parameter2) { // this is an onclick function
// some functionality
return x;
var test = x.innerHTML;
localStorage.setItem('somediv', test);
}
window.onload = function () {
var test2 = localStorage.getItem('somediv')
$('div.somediv').text(test2);
}
You are using localStorage fine.
The thing is, if you return x; in your text() function, the code below is never executed, so it never actually sets the localStorage variable.
That is why you get null when you are trying to access it.
Try this, you will get an idea.
Click me
<script>
function test(param) { // this is an onclick function
localStorage.setItem('somediv', param);
alert('ok');
}
window.onload = function () {
if(localStorage.getItem('somediv')==null){
return;
}
var test2 = localStorage.getItem('somediv')
//$('div.somediv').text(test2);
alert(test2);
}
</script>

Will HTML elements have a load success promise? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
While getting used to the concept of promises I have been wondering if elements like HTMLImageElement will have a native promise in future for a 'load' success or failure, similar to the 'load' event which already exists, but with the advantages of being able to be polled after loading?
https://www.w3.org/2001/tag/doc/promises-guide#one-time-events
Promises are definitly a good idea. The problem however is that the DOM has an event model and events and Promises don't really work well together. You can't have a promise for an onclick event for instance (well, you can, but what does it mean?) Some events, like load, may seem to make sense but what if you change the src? You'll get another load event!
Maybe someone is going to have a good idea how to unify these concepts. For now, I think we're stuck with writing code that interfaces between events and Promises.
Not as of HTML5. But I like the concept. I would love to see promise-events in HTML6.
The document you referenced is a guide for when to use promises. So, if you are creating a custom object with events, you might consider implementing a promise interface for your one-time events.
You could easily implement a library to add promise events to DOM elements today.
function loadPromise(image) {
if (image.src && image.complete) {
if (image.naturalWidth > 0) {
return Promise.resolve(image);
}
else {
return Promise.reject(new Error("image failed loading"));
}
}
return new Promise(function(resolve, reject) {
image.addEventListener("load", function(e) {
resolve(image);
}, false);
image.addEventListener("error", function(e) {
reject(new Error("image failed loading"));
}, false);
if (image.src) {
// IE reports image.complete as false when there is an error
var errTest = new Image();
errTest.onerror = function(e) {
reject(new Error("image failed loading"));
};
errTest.src = image.src;
}
});
}

Add function call as parameter to onclick function onclick="foobar(cb_func)" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm using onclick for an element, but need to pass a callback to it like this:
function cb_func() {
alert("hello world!");
}
function foobar(i, cb) {
do something
if (cb != undefined)
cb();
}
onclick="javascript:foobar(1, cb_func)"
foobar gets called, but my cb_func isn't - in fact when I step in to cb() usinf Firebug, it shows me the HTML for the entire page.
Any ideas how I might achieve this?
Use event delegation:
$(document).on('click', '.dynamicGeneratedEl', function(event){
// do something
cb_func();
});
Where .dynamicGeneratedEl is a suitable selector for your case.
comment the line // do something
function cb_func() {
alert("hello world!");
}
function foobar(i, cb) {
// do something
if (cb != undefined)
cb();
}
Try this:
https://jsfiddle.net/h3ckcgvv/2/
var nextFunction = function() {
// some more stuff happens
}
var processClick = function() {
// some stuff happens
// condition
nextFunction();
}
$('.js-click-me').click(processClick);
The condition could be anything, based on page inspection, javascript variable state, data attributes on the clicked HTML element etc. Much more stable and maintainable than onclick attributes and hardcoding the callback into every call where it's needed.

Javascript - setTimeout function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
i try to develop a page and i have to use setTimeout function because i need to load my video in my page two seconds later.
In order to do that, i wrote this,
window.onload = function () {
player = new Player('playerObject');
setTimeout(player.playByUrl($mp4Link),3000);
}
but this is not working why ?
Use callback:
setTimeout(function(){
player.playByUrl($mp4Link);
},3000);
With your previous statement, the code was executing immediately (because you were calling it directly by specifying param and parenthesis eg playByUrl($mp4Link)) whereas setTimeout needs a callback.
You cannot add parameters to the function. However you can simply use an anonymuos function as callback and call the function in there (with the parameters).
window.onload = function () {
player = new Player('playerObject');
setTimeout(function() {
player.playByUrl($mp4Link);
}, 3000);
}
setTimeout requires a function
window.onload = function () {
player = new Player('playerObject');
setTimeout(function(){
player.playByUrl($mp4Link);
},3000);
}
You need to pass a function reference to setTimeout, but I guess the return value from .playByUrl() is not a function. So either go with
setTimeout(function() {
player.playByUrl($mp4Link);
},3000);
or use ES5 .bind()
setTimeout(player.playByUrl.bind(null,$mp4Link),3000);
player.playByUrl($mp4Link) is the returned value.
try
setTimeout("player.playByUrl($mp4Link)",3000);
or
setTimeout(player.playByUrl,3000, $mp4Link);
The latter does not work with IE and so should be modified.
try to add player.load(); as follow:
player.load();
setTimeout(function(){
player.setAttribute("src","http://www.w3school.com.cn/example/html5/mov_bbb.mp4");
player.play();
},5000)

Cancel event when delay was not met? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to be able to cancel an event based on the amount of time an element is hovered on. Say when I set the delay to 500ms, when the element is being hovered on for less than that, an event should be cancelled, otherwise it is fired. The delay() and setTimeout() function seem incapable of doing that.
You can try something like this instead of using jQuery delay method.
Working demo
var timeoutId = null;
$("selector").hover(function(){
if(timeoutId)
clearTimeout(timeoutId);
timeoutId = setTimeout(function(){
alert("do your stuff here");
}, 5000);
}, function(){
clearTimeout(timeoutId);
});
Someone might come up with something cleaner but the code below will be able to handle what you are asking. It requires 500 milliseconds to pass before the code inside the event can be triggered again. Could probably clean it up so that timer/delayMet aren't potentially global variables.
I'm using $('a').click as an example selector and event.
var timer,
delayMet = true;
$('a').click(function () {
if(delayMet === true) {
// your code here
}
else {
delayMet = false;
setTimeout(function () {
delayMet = true;
}, 500);
}
});
You can cancel setTimeout() by doing the following.
var timer = setTimeout(function(){...},5000);
...
clearTimeout(timer);
From jQuery .delay() docs:
The .delay() method is best for delaying between queued jQuery
effects. Because it is limited—it doesn't, for example, offer a way to
cancel the delay—.delay() is not a replacement for JavaScript's native
setTimeout function, which may be more appropriate for certain use
cases.
Not sure if that is what you mean though.

Categories

Resources