javascript的时间和延迟

时间:2013-12-14 22:49:31

标签: javascript

我按照1和0的顺序将页面背景从白色更改为黑色。此时我设法使其工作,黑色和白色背景以相同的延迟变化:

var syncinterval = setInterval(function(){
    bytes = "10101010101010101010101010101010101010101010101010101010101010101";

    bit = bytes[i];
    output_bit(bit);

    i += 1;
    if (i > bytes.length) {
        clearInterval(syncinterval);

        i = 0;
        for (i=0; i < input.length; i++) {
            tbits = input[i].charCodeAt(0).toString(2);
            while (tbits.length < 8) tbits = '0' + tbits;
            bytes += tbits;
        }
        console.log(bytes);
    }
}, sync_speed);

完整的工作演示:http://jsfiddle.net/kn48Z/

如何修改功能,使白色背景为sync_speed秒,黑色背景为其他任何值?

2 个答案:

答案 0 :(得分:0)

如果我理解您要执行的操作,请尝试将代码放入单独的函数中并使用setTimeout。这将使您更好地控制您要完成的任务。

我修改了你的代码。我检查是否位是1(我假设是白色),如果是,它将在sync_speed秒内运行backgroundOrSomething。如果不是,它将在otherTime中运行backgroundOrSomething。我将otherTime设置为1秒,只是为了咯咯笑。

    function backgroundOrSomething (){
    bytes = "10101010101010101010101010101010101010101010101010101010101010101";

    bit = bytes[i];
    output_bit(bit);

    i += 1;
    if(i > bytes.length) {
        i = 0;
        for (i=0; i < input.length; i++) {
            tbits = input[i].charCodeAt(0).toString(2);
            while (tbits.length < 8) tbits = '0' + tbits;
            bytes += tbits;
        }
        console.log(bytes);
    }

    otherTime = 1000;

    if (bit == 1)
        setTimeout(backgroundOrSomething, sync_speed);
    else
        setTimeout(backgroundOrSomething, otherTime);
}

setTimeout(backgroundOrSomething, sync_speed);

代码底部的最后一个setTimeout将是第一个执行backgroundOrSomething的。(/ p>

答案 1 :(得分:0)

如上所述,您需要使用如下设置间隔:

var bit = 0;
var syncInterval = setInterval(function() {
    document.body.style.backgroundColor = bit == 0 ? 'black' : 'white';
    bit = 1;
}, 3000);

var stopInterval = setTimeout(function() {
    clearInterval(syncInterval);
}, 50000);

在此处http://jsfiddle.net/kn48Z/4/。注意减慢背景开关,以便它适合。

相关问题