为JavaScript函数添加延迟

时间:2015-01-12 14:25:28

标签: javascript jquery html css delay

我正在尝试了解添加代码的位置,以延迟我的div切换0.5秒。我是JavaScript / jQuery的初学者。

function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }

//it is tied to this if it can help

<a onclick="toggle_visibility('section1_1_content');toggle_visibility('note1_1');"> <div id="help_tiem_section1_1" onclick="chngimg1()" onmouseover="this.style.cursor='pointer'">
            <p1>TEST</p1><img src="down.png" height="10px" width="15px" id="imgplus1"/>
        </div></a>

这很有效。但是,我想改变它,以便当它变回显示时,它不会延迟。

2 个答案:

答案 0 :(得分:3)

使用setTimeout()

setTimeout(yourFunction, 500)

答案 1 :(得分:0)

您应该使用setTimeout

function toggle_visibility(id) {
   setTimeout(function() {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }, 500);
}

更新

function toggle_visibility(id) {
    var e = document.getElementById(id);
    if (e.style.display == 'block') {
        setTimeout(function() {
            e.style.display = 'none';
        }, 500);
    } else {
        e.style.display = 'block';
    }
}