How to create delay function in QML?

前端 未结 5 607
小鲜肉
小鲜肉 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:44

    Here's another variation which utilizes the Component object to house the Timer object.

    Then we implement a setTimeout look-a-like function to dynamically create and invoke this Timer object.

    N.B. The answer assumes Qt5.12.x which includes ECMAScript 7 (and therefore ECMAScript 6) to utilize parameter shortcuts, rest parameters and spread syntax:

        function setTimeout(func, interval, ...params) {
            return setTimeoutComponent.createObject(app, { func, interval, params} );
        }
    
        function clearTimeout(timerObj) {
            timerObj.stop();
            timerObj.destroy();
        }
    
        Component {
            id: setTimeoutComponent
            Timer {
                property var func
                property var params
                running: true
                repeat: false
                onTriggered: {
                    func(...params);
                    destroy();
                }
            }
        }
    

    In the following snippet, we will invoke console.log(31), console.log(32), console.log(33) in a random time delay between 0-1000ms from now.

    console.log("Started");
    setTimeout(console.log, Math.floor(1000 * Math.random()), 31);
    setTimeout(console.log, Math.floor(1000 * Math.random()), 32);
    setTimeout(console.log, Math.floor(1000 * Math.random()), 33);

    See also: https://community.esri.com/groups/appstudio/blog/2019/05/22/ecmascript-7-settimeout-and-arrow-functions

提交回复
热议问题