Using JS setTimeout in a bookmarklet - javascript

I am trying to run some JS code in a bookmarklet in firefox. Here's some basic code to prove the point:
window.setTimeout( function() {alert('i ran');}, 1000 );
when I run code with setTimeout in it, I get the whole page replaced by the counter value that normally gets logged in the console.
Is there a way to catch this output and stop this happening?
Thanks!

Try the following:
javascript:(window.setTimeout(function() { alert('i ran'); }, 1000));void(0);

When you use the javascript: protocol in an address bar (which is what all bookmarklets do), the browser does a document.write on whatever the return value is if it's truthy.
A setTimeout call always returns a number for the timer. To fix this you can either append a void(0); like epoch or as I like to do, wrap it in an IIFE:
(function() {
window.setTimeout( function() {alert('i ran');}, 1000 );
})();

Related

setTimeout fires twice or not in Javascript

I have this code:
window.setTimeout(function() {
let sudokuBodyWidth = $sudokuBody.outerWidth(true);
let sudokuBodyHeight = $sudokuBody.outerHeight(true);
console.log(sudokuBodyWidth + ',' + sudokuBodyHeight);
$sudoku.hide();
$welcomeOverlay.css({
width: sudokuBodyWidth,
height: sudokuBodyHeight
}).show();
}, 800);
window.clearTimeout();
I've put this code in a setTimeout because it takes a lot of time the DOM to load, so the JS code is to early with executing and returns 0 for the values (it's a huge codebase and I'm not 'allowed' to change the site structure to make the JS load later).
The problem is that this code runs twice. First, it returns the correct result, but then it returns 0 for both variables immediately after the correct values. As you can see, I've added a clearTimeout to prevent the execution to happen twice. But it keeps executing twice.
I've also tried:
let welcomeTimeout = setTimeout(function() {
// the code
});
clearTimeout(welcomeTimeout);
When doing this, the code doesn't execute at all.
window.clearTimeout() will do nothing because you are not passing the timerId witch get returned by window.setTimeout() and this should not run twice there is something else witch is causing this function to run twice
and in second one clearTimeout(welcomeTimeout); clears the timer that's why your code doesn't run
if you want to run your code after the document get loaded fully then you can use window.onload = function(){...}
or if you are using jQuery then you can also try $(document).ready(function(){...})
It should execute only once check Ur code base if u r loading script two times mean while put clearTimeout code at the end in the ananymous function given to setTimeout function
Putting the code at the end of HTML executes it when the DOM is loaded.
Use this:
<html>
<head>
<script async src="..."></script>
...
</head>
<body>
...
...
<script>(function() { init(); })();</script>
</body>
</html>
Function init() will fire when the DOM is ready.
Also you're using setTimeout() wrong, take a look at this example.
var what_to_do = function(){ do_stuff(); };
var when_to_do = 3000; // 3000ms is 3 seconds
var timer = setTimeout(what_to_do, when_to_do);

How to keep a command running in loop in browser console

I have a web element that only appears while the page (or a part of the page) is still loading and disappears when the page has been completely loaded. I would like to see precisely when this element disappears and I can do that by repeatedly running something like that in the browser console:
$("div.v-app-loading")
or alternatively:
document.getElementsByClassName('v-app-loading')
But in most cases everything happens too fast and I am unable to catch the exact moment. There must be a way to create a loop that will just run in the console and execute one of the commands I mentioned say every 0.5sec or even more frequently.
Could anyone point me to the right direction?
You can use Javascript's setInterval() as following:
function yourFunction(){
//do something here...
}
setInterval(yourFunction, 500); //Will run the function every half a second(500ms = 0.5s)
Maybe it's easier to use jQuery to detect when the page is loaded:
HTML
<body class="loading">
JS
// do something initially here
$(window).load(function () {
// do something when finished loading
$('body').removeClass('loading');
});
Edit: If you rather wanted to check for existence of an elemtent, do it in a recursive function call. You can throttle it with setTimeout, but you don't need to:
function checkElement() {
if ($('.v-app-loading').length) {
checkElement();
// or: setTimeout(checkElement, 100);
} else {
// Element disappeared
}
}
checkElement();

long run error after calling the javascript method from the action script

I am trying to call a method of a javascript from the actionscript using the ExternalInterface.
Here is the code in action script
private function onKickEvent(e:LogoutEvent):void{
ExternalInterface.call("LoginFound","message");
return;
}
And this is my javascript mwthod
function LoginFound(message){
alert(message);
anotherInstanceExists=true;
}
Everything is working fine, but the only thing is when act on the alert box which is shown in the javascript after some 20 secs, the exception is thrown from the flash player that a script has been running longer than expected time 15 sec.
How can i avoid this?
Best way to fix this issue is to add setTimeout inside your javascript on the alert line.
It should look like this:
setTimeout(function(){ alert(message) }, 1);
By doing it this way execution won't stop because of the alert.
When you call js function from the actionscript, that function have to work and return value not longer than in 15 sec. Javascript works in single thread,and when you call LoginFound function, alert stops farther executions on the thread.
function LoginFound(message){
alert('something');
//Nothing will be executed unless `alert` window will be closed
}
However you can handle such situation (the execution,which is longer than 15 sec) in Actionsript by using try/catch:
private function onKickEvent(e:LogoutEvent):void{
try{
ExternalInterface.call("LoginFound","message");
}catch(e:Error){
//Do something
}
}
I think your onKickEvent is called frequently
so that the javascript is called regularly. finally the browser timeout event
occurs. It always happen in recursive function.

How can I profile setTimeout functions existance in JS

I am having a problem understanding which function runs (probably in infinite loop) in my JS code.
Is there a plug\way to see the list of the setTimeout functions that are running?
All you have to do is hook into your setTimeout function and log stuff:
var _temp = setTimeout;
setTimeout = function() {
_temp.apply(this, arguments);
alert(arguments[0]);
};
Put that snippet at the top of your code. Every time anything invokes setTimeout, you'll see exactly who's doing it.
Also, instead of alert, use console.log or something similar.
You can probably use the Firebug Firefox extension to put a breakpoint in. http://getfirebug.com/

javascript setTimeout, page looks like is endlessly loading (firefox)

var checkTextValue = setTimeout(function() {
var textVal = $('p').text();
if (textVal == 'expectedValue'){
callback();
} else {
setTimeout(arguments.callee, 10);
}
},10);
i have this code,it works just fine but the problem is that in firefox the page looks like is endlessly loading.
Looks kind of useless... I mean setTimeout(checkTextValue, 10); - what are you setting there? checkTextValue is just a timeout ID, nothing else... No idea why FF would load endlessly, simply because the code is faulty...
That is because it is endlessly loading. Basically you do recursion and start another instance every ten milliseconds. Given enough time, I think it also is possible to kill your browser with this code.
Try using an onchange-eventhandler on your input field instead.
I think its a case of recusrsion. Google 'recusrion' for more clues. Just kidding. checkTextValue will be running indefinitely unless the value is 'expectedValue'.

Categories

Resources