如何在函数执行前等待一秒钟

时间:2016-03-30 16:29:29

标签: javascript html5 timer

如何在触摸屏幕一秒钟后执行此js功能 和 如何让它成为相同触摸位置的一秒钟..如果我一直在同一位置触摸屏幕一秒钟?

function onCanvasTouchStart(event)
{
    if(event.touches.length == 1)
    {
        // draw
        event.preventDefault();
        brush.strokeStart((event.touches[0].pageX) - canvas.offsetLeft, (event.touches[0].pageY) - canvas.offsetTop);
        window.addEventListener('touchmove', onCanvasTouchMove, false);
        window.addEventListener('touchend', onCanvasTouchEnd, false);
    }
}

2 个答案:

答案 0 :(得分:1)

使用setTimeOut

function onCanvasTouchStart( event ){
    if(event.touches.length == 1){
        setTimeout(function(){ 
           // draw
           event.preventDefault();

           brush.strokeStart( (event.touches[0].pageX) - canvas.offsetLeft, (event.touches[0].pageY) - canvas.offsetTop );

           window.addEventListener('touchmove', onCanvasTouchMove, false);
           window.addEventListener('touchend', onCanvasTouchEnd, false); 
        }, 1000);

    }

}

答案 1 :(得分:1)

function onCanvasTouchStart(event) {
    if (event.touches.length == 1) {
        setTimeout(function() {
            // draw
            event.preventDefault();

            brush.strokeStart( (event.touches[0].pageX) - canvas.offsetLeft, (event.touches[0].pageY) - canvas.offsetTop );

            window.addEventListener('touchmove', onCanvasTouchMove, false);
            window.addEventListener('touchend', onCanvasTouchEnd, false);
        }, 1000);
    }
}

这会在一秒钟之后触摸屏幕后发生,但如果您在屏幕上连续触摸1秒后需要它,那么您需要确保触摸在之前的任何时刻都没有结束这个内部函数被调用。您可以存储触摸开始/结束的日期。如果触摸开始后发生任何触摸结束,表示此setTimeout,则不会继续使用内部函数的代码。

相关问题