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

how to wait a second before function execution

本文关键字:等待 一秒钟 执行 函数      更新时间:2023-09-26

如何让这个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);
    }
}

使用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);
    }
}
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信号的触摸开始后发生了任何触摸结束,您将不会继续使用内部函数的代码。