javascript set interval run as separate thread?

前端 未结 3 712
野趣味
野趣味 2021-02-13 14:41

I want to use a timer as a fallback in case I end up in an infinite loop. It seems that set interval is the right way to do this. However, it\'s not working for me.

Fro

3条回答
  •  长情又很酷
    2021-02-13 15:01

    As has been already said - the callback to setInterval doesn't run until the infinite loop finishes. To do what you are trying to achieve - without using web workers - you have to check the time from the loop itself:

    var start = Date.now();
    while((Date.now() - start) < 5000){
      ...
    }
    

提交回复
热议问题