Why does this setInterval/[removed] code work on Chrome but not on Firefox?

后端 未结 2 496
时光说笑
时光说笑 2020-12-11 23:24

Here is a simple program that prints numbers one to ten on the browser window.

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-11 23:58

    In addition to the points by T.J. Chowder about the webkit bug, consider these two scripts and why your code specifically doesn't work like you may have expected.

    Script 1

    
    
        foo
        
    
    
        
    
    
    

    Script 2

    
    
        foo
        
    
    
        
    
    
    

     

    Results

    Script 1

    In the first, setInterval() is triggering again after the page is closed. You'll see the alert message indicating the page had executed fully, and the document is closed for writing. After that happens, you will see the document.write being triggered by the first interval. This unloads the old, previously closed document, and adds only 1
    to the page.

    Since the old document has been unloaded, the existing javascript is gone and there is nothing else to execute beyond the first iteration.

    Script 2

    In the second script, document.write is executed multiple times while the current document is still open. Since the document.write functions are executed before the document is closed naturally, the original contents of the document are never overwritten.

     

    Conclusions

    Its better to interact with DOM elements directly than to use document.write.

    There is some more good reading on it here: https://pigeoto.wordpress.com/2011/01/19/why-doesnt-document-write-work-with-setinterval/

提交回复
热议问题