Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Stray timeout" - what does the empty timeout in javascript do?

I'm going thru some legacy code and I've noticed the following line(s):

// Stray timeout
var t = setTimeout('',1);

Does it do anything? Is it really required?


There is a following question on SO: Why is setTimeout(fn, 0) sometimes useful?

The solution is to "pause" the JavaScript execution to let the rendering threads catch up. And this is the effect that setTimeout() with a timeout of 0 does. It is like a thread/process yield in C. Although it seems to say "run this immediately" it actually gives the browser a chance to finish doing some none-JavaScript things that have been waiting to finish before attending to this new piece of JavaScript.

That explains benefits of executing a function in setTimeout. But how about executing an empty string?

like image 853
Mars Robertson Avatar asked Feb 13 '23 00:02

Mars Robertson


1 Answers

setTimeout('',1)

This line does absolutely nothing. You are telling JavaScript to eval() the string ''. That does nothing.

Sometimes doing this is useful, as it "pushes the code to the bottom of the stack" to run it after the function (and whatever UI updates the browser is doing) finishes.

For example:

setTimeout(function(){
    // Work with some DOM elements, after the browser has a second to render them
}, 0);

But I can't see an empty string having any effect on anything.

EDIT: In Google Chrome, if you do setTimeout('',1) it doesn't return you anything. Normally, it would return you the timeout_id, so you could cancel it with clearTimeout. But, in Google Chrome, setTimeout('',1) returns undefined, which makes be believe it doesn't even set a timeout, since you didn't give it anything to do. So, yeah, it literally does absolutely nothing.

like image 125
Rocket Hazmat Avatar answered Feb 15 '23 16:02

Rocket Hazmat