无休止的函数调用javascript

时间:2015-03-14 22:40:18

标签: javascript

如何在javascript中进行无休止的函数调用?

func1();
console.log('next');
func1();
console.log('next');
func1();

//endless - infinite loop

没有SetIntervalSetTimeout个函数。浏览器必须响应用户操作。

2 个答案:

答案 0 :(得分:2)

您可以使用Web Worker

window.onload = function () {
    document.querySelector('#button').addEventListener('click', function () {
        alert('not blocking the UI');
    });
};

(function () {
    var code = document.querySelector('script[type="text/ww"]').textContent,
        blob = new Blob([code], {type: 'text/javascript'}),
        worker = new Worker(URL.createObjectURL(blob));

    worker.postMessage('foo');
}());
<script type="text/ww">
    function doWork() {
        var i = 20000;
        while (i-- > 0) {
            foo();
        }
    }

    function foo() {
        console.log('do the foo');
    }

    self.addEventListener('message', doWork, false);
</script>
<button id="button">Click Me and View the Console</button>

答案 1 :(得分:-1)

我可以用setImmediate做到这一点。

https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate

通过window.postMessage或process.nextTick或MessageChannel或script.onreadystatechange

实现setImmediate实现

https://github.com/YuzuJS/setImmediate/blob/master/setImmediate.js