I have seen the following working! setinterval call.
window.setInterval('checkhash();', 1);
Any idea why this is working?
normaly it is like this:
setInterval(function(){
do something
},1000);
function checkhash(){ };
I have seen the following working! setinterval call.
window.setInterval('checkhash();', 1);
Any idea why this is working?
normaly it is like this:
setInterval(function(){
do something
},1000);
function checkhash(){ };
You have several options:
1) hand over a string which is then evaluated (bad - never do this!)
window.setInterval('checkhash()', 4);
This basically runs an evaluation on the string like eval('checkhash()')
.
Important to know, is that it is evaluated in the global context, so the following will fail:
(function(){
function test(){alert("foo")};
function test2(){alert("bar")};
// will fail
setTimeout("test()",1000);
// will work
setTimeout(test2,1000);
})();
The first timeout will produce an Uncaught ReferenceError: test is not defined
, because test()
is only known in the context of your anonymous function, but not in the global space:
See example
2) hand over a function reference (the preferred way)
window.setInterval(checkhash, 4);
3) hand over an anonymous function (used, when you need to hand over parameters)
setInterval(function(){
checkhash(param1,param2);
},4);
Doing the following (common beginners mistake) is possible too:
window.setInterval(checkhash(), 4);
This will call the function immediately and hand over the return value to the timeout to be executed after the specified amount of time.
Important notes:
4
ms as per spec, so basically 0-3 will give you an interval of at least 4ms
(depending on the scheduler of course).A very good reading is John Resig's article about timers.
this should be like,
window.setInterval(checkhash, 1);
remove your quotes, and do like this.
This is one of the all the JavaScript eval
situations, which is not a good practice, if you use string as the first parameter, it automatically get converted to a anonymous function like this:
Function('checkhash();')
So why not passing the first parameter as a function, which is the other alternative and more reasonable one.
window.setInterval(function(){
checkhash();
}, 1);
or simply:
window.setInterval(checkhash, 1);
the only problem this way is sometimes you need to use JavaScript closures to keep you your variable values stable.