无限循环一个jquery函数,直到单击一个停止按钮?打开/关闭网页循环

时间:2017-06-03 06:51:10

标签: javascript jquery

这里很简单。我想在一个循环(无限)中打开和关闭一个网页窗口,直到循环被破坏。

这是我的代码。我设法通过两个单独的按钮打开和关闭窗口,但未能在循环中排列功能。

此外,打开和关闭窗口之间可能需要延迟。拆分第二个延迟,我注意到代码//在这里添加延迟?

<!DOCTYPE html>
<html>
<body>
<div class="stop">
    <button>Stop</button>
</div>

<script>
    var myWindow;
    function openWin() {
        myWindow = window.open("https://losangeles.craigslist.org/lac/bts/6159876722.html", "_blank", "width=500, height=500");
    }

    function closeWin() {
        myWindow.close();
    }

    $(document).ready(function() {
        var myWindow;,
        delay = .2; //seconds

        function loop ( delay ) {
            openWin()
            //add delay here?

            closeWin()
        }

        loop( delay );

        $("button").on("click", function() {
            $text.stop(true, false);
        })
    });
</script>

</body>
</html>

编辑:

<!DOCTYPE html>
<html>

<meta charset="utf-8">
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no,width=device-width">
<title>Cart</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 



<body>

<div class="stop">
<button>Stop</button>
</div>

<script>


var myWindow;

function openWin() {
    myWindow = window.open("https://losangeles.craigslist.org/lac/bts/6159876722.html", "_blank", "width=500, height=500");
}

function closeWin() {
    myWindow.close();

}

     $(document).ready(function() {
    var myWindow;,
    setInterval(function(){ openWin(); }, 200);
    setInterval(function(){ closeWin(); }, 400);//the 


    $("button").on("click", function() {
        $text.stop(true, false);
    })
});
</script>

</body>
</html>

2 个答案:

答案 0 :(得分:1)

这应该更好: PEN

var myWindow;
var interval;
    function openWin() {
       myWindow = window.open("https://losangeles.craigslist.org/lac/bts/6159876722.html", "_blank", "width=500, height=500");
    }

    function closeWin() {
        myWindow.close();
    }

    window.addEventListener('load',()=>{
        var myWindow;
        var delay = .2; //seconds
        var delayBeforeClose = .3;


        function loop ( delay ) {
            openWin()
            //add delay here?

            setTimeout(closeWin,delayBeforeClose*1000)
        }

        interval = setInterval(loop,(delay+delayBeforeClose)*1000)

        document.querySelector("button").addEventListener('click',()=>{
          clearInterval(interval)
        })

    });

答案 1 :(得分:0)

使用此

 $(document).ready(function() {
    var myWindow;//duplicate declartion of variable
    setInterval(function(){ openWin(); }, 200);
    setInterval(function(){ closeWin(); }, 400);//the 


    $("button").on("click", function() {
        $text.stop(true, false);
    })
});