Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why the Timer works so many times even I set its repeat = false?

Tags:

c++

qt

qml

I want to set a 800ms delay time to run a function , so I use a timer to handle it. The code is as following.But I found, at the first time, the function runs right, it just show only one console.log("here is console....."); , but when I click it again, it shows 2 consoles, and at the third click, it shows 3 consoles, and so on...

I cannot understand why this happens, can any friends explain it for me ?

import QtQuick 2.6
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    MouseArea {
        anchors.fill: parent
        onClicked: {
            delayTimer(800,function(){
                console.log("here is console.....");
                var t= Math.random();
                console.log(t);
            })

        }
    }



    Timer{
        id:dtimer
    }

    function delayTimer(delayTime, cb) {
        console.log("delayTimer is starting");
        dtimer.interval = delayTime;
        dtimer.repeat = false;
        dtimer.triggered.connect(cb);
        dtimer.start();
    }
}

after a few clicks, when I click it again, output is:

qml: delayTimer is starting
qml: here is console.....
qml: 0.27777099609375
qml: here is console.....
qml: 0.407012939453125
qml: here is console.....
qml: 0.60552978515625
qml: here is console.....
qml: 0.360107421875
qml: here is console.....
qml: 0.21942138671875
qml: here is console.....
qml: 0.252288818359375
qml: here is console.....
qml: 0.88134765625
qml: here is console.....
qml: 0.63092041015625
qml: here is console.....
qml: 0.5125732421875
like image 920
AdvancingEnemy Avatar asked Feb 06 '23 03:02

AdvancingEnemy


1 Answers

You're connecting your signal to a slot every time you call delayTimer(), so the connections accumulate and slots are invoked multiple times. I'm not familiar with qml/js, but you need to disconnect slot after timeout is triggered:

function delayTimer(delayTime, cb) {
    console.log("delayTimer is starting");
    dtimer.interval = delayTime;
    dtimer.repeat = false;
    dtimer.triggered.connect(cb);
    dtimer.triggered.connect(function(){
        dtimer.triggered.disconnect(cb);
    });
    dtimer.start();
}
like image 141
w1ck3dg0ph3r Avatar answered Feb 07 '23 18:02

w1ck3dg0ph3r