Javascript - Images not cycling/rotating - javascript

I'm working on a script to rotate/cycle through images in javascript while respecting a limit on the amount of times it cycles through the images. What I have is below:
<a id="imageurl"><img id="Rotating1" border="0"></img></a>
<script language="JavaScript">
var delay = 3000; //6000 = change to next image after 6 seconds
var cycles = 2;
var currentCycle = 0;
function RotateImages(Start, delay)
{
var a = new Array("frown.gif","grim.gif","smile.gif", "bomb.gif");
var c = new Array("url1", "url2", "url3", "url4");
var b = document.getElementById('Rotating1');
var d = document.getElementById('imageurl');
var totalCycles = cycles * a.length;
// alert ("currentCycle: " + currentCycle);
// alert ("totalCycles: " + totalCycles);
if (Start>=a.length)
Start=0;
b.src = a[Start];
d.href = c[Start];
if (currentCycle < totalCycles) {
window.setTimeout("RotateImages(" + (Start+1) + ")", delay);
currentCycle++;
}
}
RotateImages(0, delay);
</script>
The script acts like it's working when I uncomment the alert boxes. When I comment them out, the rotation seems to stop. Any ideas on what is really going on and how to fix it?
Thanks!

perhaps you would like to change this line:
window.setTimeout("RotateImages(" + (Start+1) + ")", delay);
into:
window.setTimeout("RotateImages(" + (Start+1) + ", " + delay + ")", delay);
so that the next time RotateImages is called, it will keep the delay.

One fundamental issue to take into consideration is with setTimeout. The first parameter can be a reference to a function, whether it be an actual reference or a string reference, but you cant pass parameters along with it.
To do what you want, you need to pass a anonymous function to setTimeout. Also, Riyono is right that you should also pass the delay
setTimeout(function(){ RotateImages(Start++, delay) }, delay);
As far as your alert issue, I don't know what to tell you. But I know that the above will correct some issues.

Related

Raffle thing not working

Coding problem for raffle won't work!
var i = 0;
var count;
var names = [
"Stefon",
"Garret",
"Brandon"
];
function GetRandomInt(){
return Math.floor(Math.random()*i+1);
}
function CallWinner(){
var ID = GetRandomInt();
document.write("<hr>"+names[ID]+" has won with the ID of "+id+"!");
}
do {
i++;
for(count=0;i<=names.length;){
count++;
document.write(names[count]+" has been assigned to the raffle ID, "+count+"<br>");
}
} while (i<=names.length);
For some reason this isn't working, it acts like an infinite loop or maybe it crashes the tab, it works but then it crashes the tab. Please help.
document.write is document.wrong. Please use something more modern and less prone to doing confusing things. This function tries to write to the current document. If the document has already been processed, the document will be replaced with a blank one with your argument. You don't want that; use the proper DOM methods instead.
Your GetRandomInt function is broken; it should return a random accessible index in the array, not a static number.
Try something like this instead:
const names = [
"Stefon",
"Garret",
"Brandon"
];
function GetRandomIndex() {
return Math.floor(Math.random() * names.length);
}
function CallWinner() {
const index = GetRandomIndex();
const hr = document.body.appendChild(document.createElement('hr'));
hr.textContent = names[index] + " has won with the ID of " + index + "!";
}
names.forEach((name, count) => {
const div = document.body.appendChild(document.createElement('hr'));
div.textContent = name + " has been assigned to the raffle ID, " + count;
});
CallWinner();

Several setTimeout() functions [duplicate]

I'm trying to send emails with a 10 seconds delay between. I wrote this code:
$(document).ready(function() {
for (i = 0; i < 20; i++) {
setTimeout("SendEmail(" + i + ")", 5000);
}
});
function SendEmail(id) {
$.get("mimesender.php?id=" + id, function(data) {
var toAppend = "<span> " + data + "</span>"
$("#sentTo").append(toAppend);
});
}
server side code(php) gets the id and selects the email with the specified id from the database
$query="select email from clienti where id =".$id;
then sends the email, and sends back the current email
echo email;
However, something is wrong here. It seems like the the js function waits for 5 seconds, and then displays all the 20 email addresses at once.
Can you tell me what I'm doing wrong ? any "sleep "workaround will be greatly appreciated :)
Use interval instead of loop.
Working demo: http://jsfiddle.net/xfVa9/2/
$(document).ready(function() {
var tmr;
var i=0;
tmr=setInterval(function(){
if(i<20){
SendEmail(i);
alert("Sent "+i)
i++;
}else{
clearInterval(tmr);
}
},5000)
});
You should create a function which calls itself after 5 seconds
var i=0;
function sendEmailNow() {
SendEmail(i);
++i;
if(i<20) {
setTimeout(sendEmailNow, 5000);
}
}
What happens is that you call setTimeout 20 times, just after one another, with a timeout of 5 seconds. So naturally, all emails gets sent at once. You could change the loop to look like this:
for (i=0;i<20;i++) {
setTimeout("SendEmail("+ i + ")",(i+1)*5000);
}
There's alot of other options though, and they'd depend on just what suits your specific problem best.
First, pass a function to setTimeout.
Secondly, you'd be better off if you set the timeout for the next one in the queue after the current one is finished.
In the for loop:
sendEmail(0); // start sending first
and in the callback:
, function(data) {
if(id < 19) { // if next should be sent
setTimeout(function() {
SendEmail(id + 1);
}, 5000);
}
var toAppend = "<span> " + data + "</span>"
$("#sentTo").append(toAppend);
}
Your loop is setting up 20 timers to wait 5 seconds, then letting them all go at once.
Try something like this:
var email_count = 20;
var sendMails = function(){
SendEmail(email_count--);
if(email_count > 0){
setTimeout(sendMails, 5000);
}
}
setTimeout(sendMails, 5000)
Avoid jQuery. Learn JavaScript.
var i = 0; (otherwise leak into outer scope or runtime error)
Extra closure:
window.setTimeout(
(function (j) {
return function () {
sendEmail(j);
};
}(i)),
i * 10000);
sendEmail (code style: not a constructor)
You really want to escape $id in the server-side code to prevent SQL injection.

chrome crash while setting popupWindow.innerHTML = largeString

I have to get log every minutes
var log = '';
setInterval(function(){
log += document.getElementById('div').innerHTML; //full of html tag
},60000);
and after couple hours
log.length // > 300000
and now show it in new window
var logWindow = window.open("", "MsgWindow", "width=400,height=600");
logWindow.document.getElementsByTagName("body")[0].innerHTML = log;
after this process my chrome got crashed and all freeze. any proper way to do this? I test by different pc and the results are same.
As a workaround consider creating many elements:
var log = [];
setInterval(function() {
log.push(document.getElementById('div').innerHTML);
}, 60000);
log.forEach(function(html) {
logWindow.document.body.insertAdjacentHTML('beforeend', '<span>' + html + '</span>');
});
Consider using an array of elements rather than a string to store your log. This way you can use appendChild to gradually add elements (using a loop) to logWindow and possibly avoid a crash.
Log code:
var log = [];
setInterval(function() {
log.push(document.getElementById('div'))
}, 60000);
Pop up code:
for (var i = 0; i < log.length; i++) {
logWindow.document.getElementsByTagName("body")[0].appendChild(log[i])
}

retrieving data after right-click paste

I am trying to evaluate some data entered into a textarea after a paste has occurred. When I use onkeyup it detects if fine and does the evaluation okay when the user uses Cntl-V to paste. It does nothing when they right-click and select paste. I changed to onkeyup to onpaste which detects both the Cntl-V and Right-click paste but the data is not there. I know that the onpaste is triggered before the actual paste is performed so I tried to delay the evaluation with a setTimeout(), but even with a 5 second delay it never gets the data until after function function completes. No matter what I do I can't seem to get a count of the number of items that were entered. Here is my code:
function delayStart() {
alert("delayStart() function");
var inData = " ";
setTimeout(function()
{inData = document.getElementById("loanNumberPaste").value},
5000);
var iData = inData.value;
alert("iData = " + iData);
setTimeout(fnUpdCt(iData),5000);
}
function fnUpdCt(vId) {
var strVId = vId.value;
alert("fnUpdCt() function \n" +
"vId = " + strVId);
var i;
var iVal = vId.value;
var vCt = 0;
iVal = iVal.replace(/\s/g,' ');
iVal = iVal.split(' ');
for (i=0; i < iVal.length; i++) {
if (iVal[i].length > 0) {vCt++;}
}
document.getElementById("loanNumberCount").value = vCt;
}
<textarea id="loanNumberPaste" rows=17 cols=37 tabindex="1"
onpaste="delayStart();";onkeyup="fnUpdCt(this);"></textarea>
Any advise you can provide will be greatly appreciated.
The timeout isn't working because instead of passing the function by reference you're calling it immediately and trying to return its value.
Just wrap fnUpdCt in an anonymous function and it should be fine.
setTimeout(function(){fnUpdCt(iData)},5000);
Also, you don't need to wait 5 seconds - its not the fact that its waiting x amount of time, its the fact that its asynchronous.

Using new Image().src for click tracking

I am attempting to figure out why this click tracker isn't working. The code was written by another developer so I am not entirely sure if this ever did work.
function trackSponsor(o, p) {
(new Image()).src = PATH_BASE + 'click/' + p + '/' + o + "?_cache=" + (+(new Date()));
return false;
}
From what I can gather is that when this function is called it 'creates a new image' to fire a php script asynchronously. According to Firebug, the request is made however it is 'aborted' ~30ms in. The odd thing is that it will 'sometimes' work as in 1 in every 10+ regardless of the browser.
I would much rather fix this so that it works instead of re-writing it as an ajax request.
Any help is appreciated.
Thanks in advance.
EDIT
Because of tvanfosson's post that got me thinking. I have included the line which calls the click tracker below.
<a onclick="trackSponsor(60, 15077); goToNextStep(1988, 15077, 0); return false;" href="#">view</a>
the goToNextStep() actually changes the page. I am under the impression that it would only be executed after trackSponsor() had finished.
It's actually pretty trivial to rewrite as a get request using jQuery. Rewriting it will certainly help the next developer understand what's happening and might fix your problem. I'd need to know more about the contents of the variables -- perhaps they need to be urlEncoded? -- before I could help you any more on it. You might try urlEncoding them and see what happens.
function trackSponsor(o, p) {
var url = PATH_BASE + 'click/' + p + '/' + o + "?_cache=" + (+(new Date()));
$.get(url);
return false;
}
EDIT: you might want to check that another handler isn't redirecting the browser to a new location when the event triggering the tracking is invoked. This would abort any pending requests on the page -- and might allow a few to succeed based on the timing of the requests and if the results are delivered before the page is unloaded.
"(new Image()).src = url;" just asks for browser to hit the url.
You should delay for a 50-100ms in order to be sure that tracking info were sent to the server.
function delay(a) {
for (var b = +new Date, c = 1; 0 < c; c++) {
if (0 == c % 1E3) {
var e = +new Date;
if (b > e) break;
if (e - b > a) break;
}
}
}
function trackSponsor(o, p) {
(new Image()).src = PATH_BASE + 'click/' + p + '/' + o + "?_cache=" + (+(new Date()));
delay(100);
return false;
}
I poked around Google Analytics’ ga.js, which does use the new Image() method similar to your script.
The only difference that I could see was in how the object is created. Google's script assigns the object to a variable.
var d=new Image(1,1);d.src=f;
Maybe give that a shot?
function trackSponsor(o, p) {
var i = new Image(1,1);
i.src = PATH_BASE + 'click/' + p + '/' + o + "?_cache=" + (+(new Date()));
return false;
}
It shouldn't make a difference, but is worth a shot.
Maybe try this, for avoiding Garbage Collection to make your log not be lost.
var sendLog = (function () {
var _unique = (function () { /* 产生唯一标识*/
var time = (new Date()).getTime() + '_',
i = 0;
return function () {
return time + (i++);
}
}());
var run = function (url) {
var data = window['imgLogData'] || (window['imgLogData'] = {}),
img = new Image(),
uid = _unique();
data[uid] = img; /* 防止img被垃圾处理*/
img.onload = img.onerror = function () { /* 成功或失败后销毁对象*/
img.onload = img.onerror = null;
img = null;
delete data[uid];
};
img.src = url + '&_cache=' + uid; /* 发送统计内容*/
};
return run;
}());
sendLog('http://log_');

Categories

Resources