开发者

Javascript functions through the url bar with a delay

So.. I have a webpage with a javascript function I wish to execute..

Not knowing javascript very well I exectue the function through the url bar..

javascript: Myfunct1();
javascript: Myfunct2();

Now what I really need to be able to do is a long sleep, execute the first function, sleep for a little, then execute the second function, then lo开发者_C百科op forever.. something like:

javascript: while(1) { Sleep(20000); Myfunct1(); Sleep(5000); Myfunct2() };

Obviously there isn't a 'Sleep' function.. and this is my problem.. After looking at various posts about 'setTimeout;, I tried that but have been unable to get it right.. was wondering if somebody would take pitty and a poor javascript simpleton and show me the way to do this?


have a look at setTimeout(). This will give you the delay you're looking for.

http://www.w3schools.com/js/js_timing.asp

Just pop this into your HTML before the </body> tag

<script type="text/javascript"><!--
    setTimeout(function(){ 
        Myfunct1();
        setTimeout(function(){ 
             Myfunct2();
        },5000);
    },20000);
--></script> 


You can use setInterval in conjuction with setTimeout function:

setTimeout('Myfunct1(); setInterval("Myfunct1();", 25000);', 20000);
setTimeout('Myfunct2(); setInterval("Myfunct2();", 25000);', 25000);

This will accomplish the functionality like in your example without hanging the browser. Basicallly, it will Myfunct1() after 20s, and set it to run again 25s after that. Same thing is with Myfunct2(), except that it first run after 25s.


Here's a function that allows you to call alternating functions, waiting a specified amount of time between each invocation:

function alt(fn1, tm1, fn2, tm2) {
    var curr, time;
    (function next() {
        curr = (curr === fn1) ? fn2 : fn1;
        time = (time === tm1) ? tm2 : tm1;
        window.setTimeout(function() {
            curr();
            next();
        }, time);
    })();
}

Use it like this:

alt(Myfunct1, 20000,
    Myfunct2, 5000);

This will wait 20 seconds, then call Myfunct1, then wait 5 seconds and call Myfunct2, then wait 20 seconds and call Myfunct1 again, and so on.

Here's a general purpose version that accepts any number of function/timeout pairs:

function alt() {
    var args = arguments;
    (function next(i) {
        if (i == args.length) 
            i = 0;
        window.setTimeout(function() {
            args[i]();
            next(i + 2);
        }, args[i + 1]);
    })(0);
}

It's used the same way, but can accept more than two pairs:

alt(function(){console.log("1")}, 2000,
    function(){console.log("2")}, 1000,
    function(){console.log("3")}, 5000);

If this were real code there's a lot more you could do, like verify arguments and/or specify default timeouts when not provided for any of the given functions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜