问题
Here is the code:
function getTime(j){
var stopClock= new Date();
delta[parseInt(j)]=stopClock.getMilliseconds()-start.getMilliseconds();
}
//REST OF THE CODE!!
function func(){
{
for (var i = 0; i < 6; i++){
start = new Date();
document.write('<img src="'+URL[i]+'" width="1" height="1" alt="" onload="getTime('+i+');"/>');
}
}
//SOME CODE
setTimeout(function() {
func();
},100);
However I got this error: getTime is not defined
if I declare getTime like this:
document.getTime= function (j)
There is no error but it never execute that function.
If I remover the setTimeout, it will work with no problem.
Any thoughts?
Thanks,
回答1:
You're destroying the DOM with your document.write
call. In some browsers, this also destroys global variables.
Instead of document.write
, try...
for (var i = 0; i < 6; i++){
var img = document.body.appendChild(document.createElement('img'));
img.src = URL[i];
img.width = 1;
img.height = 1;
img.onload = makeHandler(i);
}
function makeHandler(i) {
return function() {
getTime(i);
};
}
Here's a simple demonstration of the globals being cleared...
In Firefox, the second alert will be undefined
. In Chrome, the global is retained.
http://jsfiddle.net/Z9NbR/
window.foo = 'bar';
alert(window.foo); // now we have it
setTimeout(function() {
document.write('new content');
alert(window.foo); // now we don't
}, 100);
回答2:
getTime() is a pre-defined function in Javascript please change the name and it should work
回答3:
also try using settimeout like this:
setTimeout('func', 100);
does that work better on your browser?
来源:https://stackoverflow.com/questions/10239468/function-is-not-defined-after-document-write-called-in-settimeout