How to create delay function in QML?

前端 未结 5 594
小鲜肉
小鲜肉 2020-12-23 21:17

I would like to create a delay function in javascript that takes a parameter of amount of time to delay, so that I could use it do introduce delay between execution of javas

5条回答
  •  借酒劲吻你
    2020-12-23 21:34

    The answer from Bumsik Kim is great, this answer changes it slightly so that the timer can be used on a repeating basis and then stopped and reused when desired.

    The QML for the timer to add where required.

    // Allow outside access (optional)
    property alias timer: timer
    
    Timer {
        id: timer
    
        // Start the timer and execute the provided callback on every X milliseconds
        function startTimer(callback, milliseconds) {
            timer.interval = milliseconds;
            timer.repeat = true;
            timer.triggered.connect(callback);
            timer.start();
        }
    
        // Stop the timer and unregister the callback
        function stopTimer(callback) {
            timer.stop();
            timer.triggered.disconnect(callback);
        }
    }
    

    This can be used as follows.

    timer.startTimer(Foo, 1000); // Run Foo every 1 second
    timer.stopTimer(Foo); // Stop running Foo
    
    timer.startTimer(Bar, 2000); // Run Bar every 2 seconds
    timer.stopTimer(Bar); // Stop running Bar
    
    function Foo() {
        console.log('Executed Foo');
    }
    
    function Bar() {
        console.log('Executed Bar');
    }
    

提交回复
热议问题