setTimeout not working inside infinite loop

前端 未结 5 1991
花落未央
花落未央 2020-12-21 19:28
    while(true){
        window.setTimeout(function() {
            myMethod()
        }, 15000);
        }
        function myMethod() {
            alert(\"repeat\         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-21 19:58

    The trick here, I think, would be to have the check inside the setTimeout and use clearTimeout when the condition is met. Here's an example that logs a count to the console every 1.5 seconds until 0.

    function looper(time) {
      if (time > 0) {
        console.log(time);
        var timer = setTimeout(looper, 1500, --time);
      } else {
        clearTimeout(timer);
      }
    }
    
    looper(10);
    

    You would obviously change the condition to that required by your program.

    DEMO

提交回复
热议问题