print javascript while loading - javascript

This is my code:
function myFunction(text, word){
var pos1;
do{
pos1 = text.indexOf(word);
if(pos1 !== -1){
document.getElementById("id1").innerText = pos1;
}
}while(pos1 == -1);
}
myFunction(text, "sun");
myFynction(text, "rain");
myFynction(text, "gold");
myFynction(text, "hello");
myFynction(text, "laptop");
myFynction(text, "tree");
I get text from file_get_contents of a page.
This page is continuously updating so, slowly, i will find those words through myFunction. What I want is to print those function meanwhile they finish

I really don't know if it's possible to use javascript to continuously monitor the HTML that is being loaded into the current page. It would require a few tests. However this would be my approach. (This function stops after finding one of the words in the array and displaying the pos)
var words = ['sun', 'rain', 'gold', 'HTML'];
function myFunc() {
var text = document.body.innerHTML;
var pos1;
for (var i=0; i < words.length; i++) {
pos1 = text.indexOf(words[i]);
if(pos1 !== -1){
document.getElementById("id1").innerText = pos1;
break;
}
}
if (pos1 === -1) {
// wait 1 second, try again
setTimeout(myFunc, 1000);
}
}
myFunc();
<div id='id1'></div>

Related

Displaying image from array in Javascript in setTimeInterval method

I am having little bit difficulty time pausing the image, so it gets rendered. I have images stored in even index in an array (for example: 2, 4, 6). And using for loop, I want to change the image every 2 seconds. On the load of the HTML page, I call onLoad = executeOnLoad() in HTML. The image changes from default to the image that is in sixth index, but after that it is not changing. It stays on that same index although, the console says the i is changing.
function executeOnLoad(){
for(var i = 0; i < 7; i++){
if (i%2 == 0) {
console.log("started.."+i);
displayImage(i);
}
}
}
function displayImage(i){
console.log("displaying...." + i);
document.getElementById("initial_image").src = contentArray[i];
}
window.setInterval("executeOnLoad()", 1000);
This is the console output that repeats every 1 sec but image is not changing:
started..0
displaying....0
started..2
displaying....2
started..4
displaying....4
started..6
displaying....6 < ---- The image here is displayed but, not changing to other..
I appreciate your help. Thanks.
I've created a fiddle for you that shows even numbers.
I've used the if statement instead of the for loop you had because that would run all the loop in one go.
See it working here:
var contentArray = ["0.png","1.png","2.png","3.png","4.png","5.png","6.png","7.png","8.png"]
var i = 0;
var numberOfImagesToDisplay = 6;
var speedOfAnimation = 1000;
function executeOnLoad(){
if(i <= numberOfImagesToDisplay){
if (i%2 == 0) {
displayImage(i);
i = i+2;
} else {
i++;
}
} else {
i=0;
displayImage(i);
}
}
function displayImage(img){
document.getElementById("initial_image").src = "http://www.marcelogil.com/fiddle/jsloop/" + contentArray[img];
}
window.setInterval("executeOnLoad()", speedOfAnimation);
<img src="http://www.marcelogil.com/fiddle/jsloop/0.png" id="initial_image" />
There is no pause in your code. That loop just runs through all of your images and therefore only the last one will "stick".
You can fix this by using settimeout:
console.clear();
document.body.innerHTML = '';
//START
var contentArray = [
'https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg',
'https://pixabay.com/static/uploads/photo/2016/01/14/01/41/image-view-1139204_960_720.jpg',
'https://i.vimeocdn.com/video/552738927_1280x720.jpg',
'https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg',
'https://pixabay.com/static/uploads/photo/2016/01/14/01/41/image-view-1139204_960_720.jpg',
'https://i.vimeocdn.com/video/552738927_1280x720.jpg',
'https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg',
'https://pixabay.com/static/uploads/photo/2016/01/14/01/41/image-view-1139204_960_720.jpg',
'https://i.vimeocdn.com/video/552738927_1280x720.jpg',
'https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg',
'https://pixabay.com/static/uploads/photo/2016/01/14/01/41/image-view-1139204_960_720.jpg',
'https://i.vimeocdn.com/video/552738927_1280x720.jpg',
'https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg',
'https://pixabay.com/static/uploads/photo/2016/01/14/01/41/image-view-1139204_960_720.jpg',
'https://i.vimeocdn.com/video/552738927_1280x720.jpg',
'https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg',
'https://pixabay.com/static/uploads/photo/2016/01/14/01/41/image-view-1139204_960_720.jpg',
'https://i.vimeocdn.com/video/552738927_1280x720.jpg',
'https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg',
'https://pixabay.com/static/uploads/photo/2016/01/14/01/41/image-view-1139204_960_720.jpg',
'https://i.vimeocdn.com/video/552738927_1280x720.jpg'
]
var initImg = document.createElement("img");
initImg.id = "initial_image";
initImg.src = '';
document.body.appendChild(initImg);
function executeOnLoad() {
for (var i = 0; i < 7; i++) {
if (i % 2 == 0) {
(function (a) {
setTimeout(function () {
console.log("started.." + a);
displayImage(a);
}, 1000 * (a + 1))
})(i);
}
}
}
function displayImage(i) {
console.log("displaying...." + i, contentArray[i]);
document.getElementById("initial_image").src = contentArray[i];
}
executeOnLoad();
See this code, with some small changes. The interval does not have a loop inside it, but a single action. Each time the setInterval callback is called (i.e every one second) it goes one step further, until reaching the maximum desired length (which is 7, but should probably be contentArray.length) and then the interval clears itself. Clearing the interval is possible thanks to saving a refernce to it when declaring it (var interval = window.setInterval(...) and using the clearInterval method.
var i = 0, interval;
function executeOnLoad(){
i++;
if (i%2 == 0) {
console.log("started.."+i);
displayImage(i);
}
if (i >= 7) {
clearInterval(interval);
}
}
function displayImage(i){
console.log("displaying...." + i);
document.getElementById("initial_image").src = contentArray[i];
}
interval = window.setInterval(executeOnLoad, 1000);
Check this:
var i = 0;
var contentArray = [];
contentArray.push('https://img.utdstc.com/icons/256/beautiful-life-quotes-android.png');
contentArray.push('https://img.utdstc.com/icons/monospace-android.png');
contentArray.push('https://img.utdstc.com/icons/cloud-print-android.png');
contentArray.push('https://img.utdstc.com/icons/120/desire-the-game-for-couples-android.png');
function displayImage(){
console.log("displaying...." + i);
if(i < ((contentArray.length) - 1)){
i++;
}else{
i = 0;
}
document.getElementById("initial_image").src = contentArray[i];
window.setTimeout( displayImage, 4000);
}
displayImage();
<img id="initial_image"/>
See a working example on JSFiddle

How to make sense of this javascript code [duplicate]

My question is how can I decode this JavaScript and how is encoded (with which program or online tool).
Here is the JavaScript that I want to decode:
http://pastebin.com/hZvKySjj
Every obfuscated script needs some kind of eval. In here, the lines
_L = 'constr\x75\x63\x74\x6F\x72';
[][_L][_L](_Z[_h._t4](_F))();
are doing this. _L is the string "constructor", and [].constructor.constructor is the Function constructor. It will be called with the decoded script, and the resulting function will be called. We can substitute it with an alert, paste the script in the console*, and wait for the result - we don't even need to understand how the decoding works. In your case, the result is (yes, including all the comments and linebreaks):
var alarm ="0";
var content = document;
if ((content.getElementById("wrapper") != null))
{
document.getElementById('wrapper').style.display = 'block';
}
function a ()
{
if ((content.getElementById("links") != null))
{
var temp = content.getElementById("links").innerHTML;
if ((temp.indexOf('nofollow')+1) > 0) alarm = "1";
else if ((temp.indexOf('noindex')+1) > 0) alarm = "1";
}
else alarm = "1";
}
function b ()
{
if ((content.getElementById("aa") != null) && (content.getElementById("ab") != null))
{
temp = document.getElementById("aa").href;
if ("http://uc-portaller.ru/" != temp) alarm = "1";
temp = document.getElementById("ab").innerHTML;
if ("скрипты для ucoz" != temp) alarm = "1";
}
else alarm = "1";
}
function c ()
{
if ((content.getElementById("ba") != null) && (content.getElementById("bb") != null))
{
temp = content.getElementById("ba").href;
if ("http://austere.ru/" != temp) alarm = "1";
temp = content.getElementById("bb").innerHTML;
if ("доска объявлений" != temp) alarm = "1";
}
else alarm = "1";
}
function d ()
{
if ((content.getElementById("ca") != null) && (content.getElementById("cb") != null))
{
temp = content.getElementById("ca").href;
if ("http://www.for-creative.com/" != temp) alarm = "1";
temp = content.getElementById("cb").innerHTML;
if ("темы для ucoz" != temp) alarm = "1";
}
else alarm = "1";
}
a ();
if (alarm == "0") b ();
if (alarm == "0") c ();
if (alarm == "0") d ();
if (alarm == "1") prompt('Нарушены условия использования, по всем вопросам обращайтесь в ICQ:', '376880395');
$(document).ready(function(){
//When you click on a link with class of poplight and the href starts with a #
$('a.poplight[href^=#]').click(function() {
var popID = $(this).attr('rel'); //Get Popup Name
var popURL = $(this).attr('href'); //Get Popup href to define size
//Pull Query & Variables from href URL
var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
//Fade in the Popup and add close button
$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('');
//Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accomodate for the padding + border width defined in the css
var popMargTop = ($('#' + popID).height() + 80) / 2;
var popMargLeft = ($('#' + popID).width() + 80) / 2;
//Apply Margin to Popup
$('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
//Fade in Background
$('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
$('#fade').css({'filter' : 'alpha(opacity=0)'}).fadeIn(); //Fade in the fade layer
return false;
});
//Close Popups and Fade Layer
$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
$('#fade , .popup_block').fadeOut(function() {
$('#fade, a.close').remove();
}); //fade them both out
return false;
});
});
$.fn.tabs = function () {
return this.each(function () {
var $tabwrapper = $(this);
var $panels = $tabwrapper.find('> div');
var $tabs = $tabwrapper.find('> ul a');
$tabs.click(function () {
$tabs.removeClass('selected');
$(this).addClass('selected');
$panels
.hide() // hide ALL the panels
.filter(this.hash) // filter down to 'this.hash'
.show(); // show only this one
return false;
}).filter(window.location.hash ? '[hash=' + window.location.hash + ']' : ':first').click();
});
};
$(document).ready(function () {
// console.log(window.location.hash);
$('div.tabs').tabs();
});
*) Of course you need to be sure what you're doing. There's always a small risk that it's a malicious script, and you might have not found all evals. #jfriend00's tip on executing the decoding snippets line-by-line is a safer way.
The only way I know of to understand what this code does is to find a safe environment (in case the code has malicious intent) and execute it line-by-line in a debugger and watch what it does as it deobfuscates itself to turn itself into normal javascript. The variable names will often stay obscured, but the giant string in _O will get decoded into something (probably javascript code).
Have a look at: http://www.labnol.org/software/deobfuscate-javascript/19815/
They show you how can you do something like that, it's basically a matter of using chrome debugger to "beautify" the code and make it easier to read.
Some versions of chrome don't have the command on a context menu, just look for the command "Pretty print" (has a icon like -> {})
Once done that, you can use a javascript console to evaluate small snippets of code to reverse engineer it. Eg. the expression (at the beginning of your code)
1) (s\u0065lf + ([] * 0) * 1)
2) '\x5B'
3) ((s\u0065lf + ([] * 0) * 1)[0 ^ 0] == '\x5B')
returns this string on my browser
1) "[object Window]0"
2) "["
3) true
Just find the starting point and follow from there. Obfuscated code follows the same rules as normal one, it's just all messed up.

Nonconcurrent async recursion

My end goal is to mitigate as much lag (window freezing/stuttering) as possible, giving the client a responsive window from page load.
My program is a Chrome extension, and part of it needs to search through a reddit submission, including all comments for certain words and then do some stuff with them. After this answer, I converted my code to use setInterval for the recursive search. Unforutnately, this runs concurrently, so even though each branch in the comment tree is delayed from its parent, the overall search overlaps each other, negating any benefit in the delay.
I have a solution, but I don't know how to implement it.
The solution would be to have a callback when a branch runs out that goes to the nearest parent fork. This in effect would traverse the comment tree linearly and would allow the setInterval (or probably setTimeout would be more appropriate) to have a noticeable affect.
The code that would need to be changed is:
function highlightComments(){
var elems = $(".content .usertext-body > .md");
var index = 0;
var total = elems.length;
console.log("comments started");
var intId = setInterval(function(){
highlightField(elems.get(index));
index++;
if(index == total){
clearInterval(intId);
addOnClick();
console.log("comments finished");
}
}, 25);
}
and highlightField is:
function highlightField(node) {
var found = $(node).attr("data-ggdc-found") === "1";
var contents = $.makeArray($(node).contents());
var index = 0;
var total = contents.length;
if (total == 0){
return;
}
var intId = setInterval(function() {
if (contents[index].nodeType === 3) { // Text
if (!found){
//Mods
var content = contents[index].nodeValue.replace(new RegExp(data.mods.regex, "gi"), data.mods.replacement);
//Creators
content = content.replace(new RegExp(data.creators.regex, "gi"), data.creators.replacement);
//Blacklist
for (var key in data.blacklist.regex){
if(data.blacklist.regex.hasOwnProperty(key)){
content = content.replace(new RegExp(data.blacklist.regex[key], "gi"), data.blacklist.replacement[key]);
}
}
if (content !== contents[index].nodeValue) {
$(contents[index]).replaceWith(content);
}
}
} else if (contents[index].nodeType === 1) { // Element
highlightField(contents[index]);
}
index++;
if(index == total){
clearInterval(intId);
}
}, 25);
}

Cycle css div left with an array in javascript

This code goes direct to the last position of the array, what I want is to iterate or cycle through them all and at the last position go to the first of the array. I'm tried something else but it gave me an error parsing left in firefox. This is the code fiddle Demo.
Body:
<div id="placeDiv">ok</div>
<script>
var times = ["2px","2000px","200px","12px","20px","200px","2000px"];
var move=times;
var i=0;
if(i == move.length-1)
{i=0;}
else
{i=i+1;};
document.getElementById("placeDiv").style.left=move[i];
</script>
Css:
<style>#placeDiv{position:absolute;top:0px;width:100px;height:100px;background-color:purple}</style>
This code does not work:
var times = [];
for (var i = 0; i < 30000; i++) {
times.push("\""+i+"px\"");
} var move=times;
if(i == move.length-1)
{i=0;}
else
{i=i+1;};
document.getElementById("placeDiv").style.left=move[i];
With the code above I get a this error in firefox:
Error in parsing value for 'left'. Declaration dropped.
You will need to use setTimeout here. For example:
var times = ["2px", "20px", "30px", "12px", "20px", "200px", "20px"],
move = 0,
div = document.getElementById("placeDiv");
setTimeout(function next() {
div.style.left = times[move++ % times.length];
setTimeout(next, 1000)
}, 1000);
To cycle an array values it's very useful to use % operator.
Demo: http://jsfiddle.net/m6w6K/1/
Or with setInterval:
function makeMove() {
div.style.left = times[move++ % times.length];
}
setInterval(makeMove, 1000);
Demo: http://jsfiddle.net/m6w6K/4/
Try this:
function sleep(millis, callback) {
setTimeout(function()
{ callback(); }
, millis);
}
var times = ["2px","20px","20px","12px","20px","2000px","20px"];
var move=times;
var i=0;
(function foobar_cont(){
if(i == move.length-1) {i=0;}
else {i=i+1;};
document.getElementById("placeDiv").style.left=move[i];
sleep(1000, foobar_cont);
})();
Demo
I've taken dfsq's original answer, and added some spice to it:
$(div).animate({left: times[move++ % times.length]}, 500);
Demo
There was a syntax error in your codes ... Link . It works very well for me but .. the "times" or transition is not visible to the user .. cause its to fast. :)
<div id="placeDiv">ok</div>
<script>
var times = ["2px","2000px","200px","12px","20px","200px","2000px"];
var move=times;
var i=0;
if(i == move.length-1)
{i=0;}
else
{i=i+1;}
document.getElementById("placeDiv").style.left=move[i];
</script>

Simple jQuery airport text effect, need to stop, clear change on fly?

I love to use this simple code here
http://www.unwrongest.com/projects/airport/
and it will be use on my web for weather display
http://www.xaluan.com
the idea is: the temperature will jump from 00 to current temp , it look nice and live..
The issue is, when i change the temp from C to F, or change location of Temp, the temp will need to change then the text effect need to be change on fly too..
but i have try many time even use .stop or .clearQue to restart effect but not success.
it messing up, some case dont run, some case the array of effect is become of combine two array.. i totaly lost, thank for any adivices
this is narrow simple code for statup test:
<span id="tempnow" class="tempnow">30</span>
<span onclick="changeC()">°F</span>
<span onclick="changeF()">°C</span>
<script>
// fist time run will be:
$(function($){
$('#tempnow').airport(['00','34']);
});
function changeF () {
$('#tempnow').airport([ '00', '91' ]);
}
function changeC () {
$('#tempnow').airport([ '00', '34' ]);
}
(function($){
$.fn.extend({
airport: function(array) {
var self = $(this);
var chars = ['0','9','8','7','6','5','4','3','2','1','-'];
var longest = 0;
var items = items2 = array.length;
function pad(a,b) { return a + new Array(b - a.length + 1).join(' '); }
$(this).empty();
while(items--)
if(array[items].length > longest) longest = array[items].length;
while(items2--)
array[items2] = pad(array[items2],longest);
spans = longest;
while(spans--)
$(this).prepend("<span class='c" + spans + "'></span>");
function testChar(a,b,c,d){
if(c >= array.length)
setTimeout(function() { testChar(0,0,0,0); }, 1000);
else if(d >= longest)
setTimeout(function() { testChar(0,0,c+1,0); }, 1000);
else {
$(self).find('.c'+a).html((chars[b]==" ")?" ":chars[b]);
setTimeout(function() {
if(b > chars.length)
testChar(a+1,0,c,d+1);
else if(chars[b] != array[c].substring(d,d+1).toLowerCase())
testChar(a,b+1,c,d);
else
testChar(a+1,0,c,d+1);
}, 20);
}
}
testChar(0,0,0,0);
}
});
})(jQuery);
</script>
I put the jsbin here hope some one can help me by code
http://jsbin.com/onaqis/7/edit#source
thanks..
Here's a hackish workaround: http://jsfiddle.net/EUKuS/
You need to take the following line out to break the endless cycle:
if(c >= array.length)
setTimeout(function() { testChar(0,0,0,0); }, 1000); // <----- COMMENT OUT!
else if(d >= longest)
Should work but fixing the plugin would be better.

Categories

Resources