Reputation: 3095
I've written a script that fires off 2 URLs based on some random number logic and I'm trying to set a delay before either one is fired (of half a second) but I don't think it's working properly. Am I doing this correctly? Code is below:
var clicks = "http://www.urlone.com";
var impressions = "http://www.urltwo.com";
var randomNumber = (Math.random()*100);
function callOut() {
for (var i = 0; i < lengthVal; i++){
if (randomNumber < 75) {
var randomCounter = (Math.random()*100);
if (randomCounter < 50) {
setTimeout("image1.src = clicks;",500);
}
else if (randomCounter > 50) {
setTimeout("image1.src = impressions;",500);
}
}
}
}
Upvotes: 0
Views: 165
Reputation: 3095
Duly noted about using setTimeout with a string. Here is how I ended up doing it. Is this the 'best' way to do this?
var clicks = "http://www.urlone.com";
var impressions = "http://www.urltwo.com";
var conversions = "http://www.urlthree";
var lengthVal = (Math.random() * 20 + 20);
var image1 = new Image();
var image2 = new Image();
var globalCounter = -1;
function callOut() {
var ord = (Math.random() * 9999999999999) + "";
var randomNumber = (Math.random() * 100); // Random value for each call
if (randomNumber < 75) {
var randomCounter = Math.random() * 100;
alert(randomCounter);
if (randomCounter < 50) {
image1.src = clicks + ord + "?";
}
if (randomCounter > 50) {
image2.src = impressions + ord + "?";
}
}
if (globalCounter++ < lengthVal) {
setTimeout(callOut, 1000); // Call itself after another second
}
}
Upvotes: 0
Reputation: 23562
setTimeout("image1.src = clicks;",500);
For this image1
must be declared in a global context, like this:
var image1 = document.getElementById('image1');
But you better use a function here.
function setImageSrcClicks(){
document.getElementById('image1').src = 'http://clicks_url';
}
setTimeout(setImageSrcClicks,500);
Upvotes: 0
Reputation: 37177
Taken from here: http://www.codescream.com/?p=18 read it it should help :)
If you want to make a delay with setTimeout you should do exactly this:
setTimeout( function () {
doThings()
}, 1000);
and never this:
setTimeout( "doThings()", 1000);
Upvotes: 1
Reputation: 150303
setTimeout
first parameter should be a function. Not string of code.
code in the alternate syntax, is a string of code you want to execute after delay milliseconds. (Using this syntax is not recommended for the same reasons as using eval())
setTimeout(function(){...}, 500);
Upvotes: 1