Can someone help me with a small JavaScript setTimeout problem? - javascript

I want to cut down the numbers of the event execution time
and so I wrote something like this:
var slow=function(method,context){
method.id&&clearTimeout(method.id)
method.id = setTimeout(function(){
method.apply(context,arguments)
}, 500)
}
window.onload=function(){
function print(){ console.log("thanks a lot") }
document.body.addEventListener("mousemove",function(){
slow(print)
}, false)
}
If I move too fast in the body, and the print function won't be executed immediately, but it doesn't seem to be work.
Can somebody help?

At first look, You have'nt provided the context parameter in the call to slow

I'd suggest using Ben Alman's throttle/debounce plugin. It doesn't actually require jQuery at all. If you don't have jQuery on the page, it just adds itself to the Cowboy namespace.
https://github.com/cowboy/jquery-throttle-debounce/blob/master/jquery.ba-throttle-debounce.js
Otherwise, you could at least get a good idea of how he does this from the code here.

Related

Make Jquery take a short break

Im trying to make my program just chill out for 3 sekunds and then proceed with the rest of the code - but all the stuff i can finde online just delays specifit lines of code (any way not what i was looking for)
What i wish to do is something like this
$("#one").attr("id","H1");
$("#line1").attr("id","line2");
setTimeout(3000);
$("#line2").attr("id","line1");
$("#H1").attr("id","two");
And it should just chillout for 3 sekunds where i have placed the settimeout(3000); but can make it work ? im i missing something obvious ?
Thanks alot ! :D
setTimeout() takes a function, then the delay:
setTimeout(function() {
$("#line2").attr("id","line1");
$("#H1").attr("id","two");
}, 3000);
Note that setTimeout() delays what's inside this function.
setTimeout() does not block the execution of the rest of your code,
so the following code would do exactly what console.log() says:
console.log("I log first!");
setTimeout(function() {
console.log("I log third!");
},1000);
console.log("I log second!");
Normally when someone wants JavaScript, which is a single-thread event-based model, to sleep, they do not quite understand the language.
You are not supposed to block code. Instead, you should make use of callbacks, event triggers or Promises to run dependent code when you have the dependencies.
Please read through this entire question so that you understand better what it is you are trying to do, and then decide which action to take.

Reload page every 5 seconds - external JS

Okay. The issue I am having is I am simply trying to do a refresh loop for my webbrowser (firefox) I would like this in JS. I understand It can be done in other languages pretty easily if you ask me. But, javascript is a must! :D This is not an html page, just a simple .js file ran with iMacros for Firefox.
Here's the code I am using.
setInterval(refreshPage(), 5000);
function refreshPage() {
window.location.reload(1);
}
window.location.reload(1); refreshes the page without a problem :D sweet!!!
But when I use the setInterval or setTimeout mumbojumbo I always get ReferenceError: setTimeout is not defined...
Very strange. I Googled so hard and all searches return the same setInterval and same setTimeout options... no one is defining anything. o_O what in the world! lol
Can one of you JS WIZARDS crack this code. I need a WIZARD to save me :D
Your question is not clear. Your code uses setInterval, but your error is about setTimeout.
Let me assume that you want and use setInterval because that makes more sense as you want to refresh the page every 5 seconds.
The setInterval function is defined by the browser. It requires a function name as first argument. You passed in a function call.
To fix it, simple delete the pair of parentheses:
setInterval(refreshPage, 5000);
function refreshPage() {
window.location.reload(1);
}
That is because you are looking for
window.setInterval(function(){refreshPage()}, 5000);
Could also just call the function as noted in the comments:
window.setInterval(refreshPage, 5000);

Why is this setTimeout not working & related question inside

I have this script on a page of mine and the setTimeout function never fires. It's just an alert right now but i'm just testing it out. I'm doing a meta refresh on the page just after it if that's any clue, but i've also given that a 10 sec delay so the page isn't refreshed before it's supposed to trigger.
Also, the related question: If I run a javascript with a delay of, say, 10 seconds (with setTimeout) and in that javascript I try to modify a design element that's not on the page when the setTimeout is declared but will be by the time the script is fired. Will it work?
<script language=javascript>
var xmlhttp_get_memento;
function loop_alerte(){
setTimeout( function() {
alert("timeout");
}, 5000);
xmlhttp_get_memento = new XMLHttpRequest();
if (xmlhttp_get_memento==null)
{
alert ("Browser does not support HTTP Request (1)");
return;
}
var url="crm/ajax/get_mementos.php";
url=url+"?sid="+Math.random();
xmlhttp_get_memento.onreadystatechange=function() {
if (xmlhttp_get_memento.readyState == 4) {
alert(xmlhttp_get_memento.responseText);
schimbare_tip_cursor("default");
}
else{
schimbare_tip_cursor("progress");
}
};
xmlhttp_get_memento.open("GET",url,true);
xmlhttp_get_memento.send(null);
}
loop_alerte();
</script>';
Your setTimeout looks good, so there's probably something else that's wrong. Have you tried using a javascript debugger to see if you get any errors?
As for your second question, yes, that shouldn't be any problem, as the anonymous function inside the setTimout won't be evaluated until it runs. Live sample here: http://jsbin.com/afonup/2/edit Both with and without jQuery.
There is nothing wrong with your setTimeout, you will need to debug further
As for your second question -- the function will run, but whatever it is you were trying to do will not work.
Cleaning up your code would be a nice start. I can imagine a browser doesn't understand the tag <script language=javascript>. I suggest to use <script type="text/javascript"> and if you're lucky, your javascript might work!

jquery/js : best way to have an image fading in and out? (recursion?)

Is there a better way than this, for two images positioned over each other where #state_2 is the top image.
function recursive_fade(){
$('#top_img').delay(4000).fadeOut(400).delay(4000).fadeIn(400);
recursive_fade();
};
$(function(){
recursive_fade();
});
When i dynatrace this, it seems to use fair bit of cpu...
You should use continuation-style here: let the fx system call the recursive_fade when the last animation has finished:
function recursive_fade(){
$('#top_img')
.delay(4000)
.fadeOut(400)
.delay(4000)
.fadeIn(400, recursive_fade );
};
EDIT 2 - meanwhile, it seems (long liveth the jQuery forum) that the Effects are implemented using a queue and the setTimeout function - making EDIT 1 obsolete.
EDIT - since I have no idea if jQuery allows this recursion (I didn't find convincing proof), I think it's best to combine the "Timeout" suggestions with the continuation technique like so:
function recursive_fade(){
$('#top_img')
.delay(4000)
.fadeOut(400)
.delay(4000)
.fadeIn(400, function() { setTimeout( recursive_fade, 0 ); } );
};
This offers the guarantee that stack won't blow up, yet avoids the need to calculate the timeout interval.
I wouldn't do it recursively, I would use a setTimeout so it doesnt totally lock up the browser.
function recursive_fade(){
$('#top_img').delay(4000).fadeOut(400).delay(4000).fadeIn(400);
setTimeout(function(){recursive_fade(); },8800);
};
$(function(){
recursive_fade();
});
How about using setInterval(). Info here.
Something like this:
function fadeShow() {
$('#top_img').delay(4000).fadeOut(400).delay(4000).fadeIn(400);
}
$(function() {
setInterval(fadeShow, 8800);
}

How can I tell when changes to jquery html() have finished?

I'm using jQuery to change the HTML of a tag, and the new HTML can be a very long string.
$("#divToChange").html(newHTML);
I then want to select elements created in the new HTML, but if I put the code immediately following the above line it seems to create a race condition with a long string where the changes that html() is making may not necessarily be finished rendering. In that case, trying to select the new elements won't always work.
What I want to know is, is there an event fired or some other way of being notified when changes to html() have finished rendering ? I came across the jQuery watch plugin, which works alright as workaround but it's not ideal. Is there a better way ?
As a commenter already mentioned, JavaScript is single threaded, so you can't get race conditions.
What may trip you up however, is the fact that the UI will not update itself based on JavaScript, until a thread is finished. This means that the entire method must finish, including all code after you call html(...), before the browser will render the content.
If your code after calling html(...) relies on the layout of the page being recalculated before continuing, you can do something like this:
$("#divToChange").html(newHTML);
setTimeout(function() {
// Insert code to be executed AFTER
// the page renders the markup
// added using html(...) here
}, 1);
Using setTimeout(...) with a time of 1 in JavaScript defers execution until after the current JavaScript code in the calling function finishes and the browser has updated the UI. This may solve your problem, though it is difficult to tell unless you can provide a reproducible example of the error you're getting.
use .ready jQuery function
$("#divToChange").html(newHTML).ready(function () {
// run when page is rendered
});
It's 7 years latter and I just ran into a scenario exactly like the one #mikel described, where I couldn't avoid a "timer based solution". So, I'm just sharing the solution I developed, in case anyone out there is still having issues with this.
I hate having setTimeouts and setIntervals in my code. So, I created a small plugin that you can put where you think it's best. I used setInterval, but you can change it to setTimeout or another solution you have in mind. The idea is simply to create a promise and keep checking for the element. We resolve the promise once it is ready.
// jquery.ensure.js
$.ensure = function (selector) {
var promise = $.Deferred();
var interval = setInterval(function () {
if ($(selector)[0]) {
clearInterval(interval);
promise.resolve();
}
}, 1);
return promise;
};
// my-app.js
function runWhenMyElementExists () {
// run the code that depends on #my-element
}
$.ensure('#my-element')
.then(runWhenMyElementExists);

Categories